Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot._typing import E
  25from sqlglot.errors import ParseError
  26from sqlglot.helper import (
  27    AutoName,
  28    camel_to_snake_case,
  29    ensure_collection,
  30    ensure_list,
  31    seq_get,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39
  40class _Expression(type):
  41    def __new__(cls, clsname, bases, attrs):
  42        klass = super().__new__(cls, clsname, bases, attrs)
  43
  44        # When an Expression class is created, its key is automatically set to be
  45        # the lowercase version of the class' name.
  46        klass.key = clsname.lower()
  47
  48        # This is so that docstrings are not inherited in pdoc
  49        klass.__doc__ = klass.__doc__ or ""
  50
  51        return klass
  52
  53
  54class Expression(metaclass=_Expression):
  55    """
  56    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  57    context, such as its child expressions, their names (arg keys), and whether a given child expression
  58    is optional or not.
  59
  60    Attributes:
  61        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  62            and representing expressions as strings.
  63        arg_types: determines what arguments (child nodes) are supported by an expression. It
  64            maps arg keys to booleans that indicate whether the corresponding args are optional.
  65        parent: a reference to the parent expression (or None, in case of root expressions).
  66        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  67            uses to refer to it.
  68        comments: a list of comments that are associated with a given expression. This is used in
  69            order to preserve comments when transpiling SQL code.
  70        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  71            optimizer, in order to enable some transformations that require type information.
  72
  73    Example:
  74        >>> class Foo(Expression):
  75        ...     arg_types = {"this": True, "expression": False}
  76
  77        The above definition informs us that Foo is an Expression that requires an argument called
  78        "this" and may also optionally receive an argument called "expression".
  79
  80    Args:
  81        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  82    """
  83
  84    key = "expression"
  85    arg_types = {"this": True}
  86    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  87
  88    def __init__(self, **args: t.Any):
  89        self.args: t.Dict[str, t.Any] = args
  90        self.parent: t.Optional[Expression] = None
  91        self.arg_key: t.Optional[str] = None
  92        self.comments: t.Optional[t.List[str]] = None
  93        self._type: t.Optional[DataType] = None
  94        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  95        self._hash: t.Optional[int] = None
  96
  97        for arg_key, value in self.args.items():
  98            self._set_parent(arg_key, value)
  99
 100    def __eq__(self, other) -> bool:
 101        return type(self) is type(other) and hash(self) == hash(other)
 102
 103    @property
 104    def hashable_args(self) -> t.Any:
 105        return frozenset(
 106            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
 107            for k, v in self.args.items()
 108            if not (v is None or v is False or (type(v) is list and not v))
 109        )
 110
 111    def __hash__(self) -> int:
 112        if self._hash is not None:
 113            return self._hash
 114
 115        return hash((self.__class__, self.hashable_args))
 116
 117    @property
 118    def this(self):
 119        """
 120        Retrieves the argument with key "this".
 121        """
 122        return self.args.get("this")
 123
 124    @property
 125    def expression(self):
 126        """
 127        Retrieves the argument with key "expression".
 128        """
 129        return self.args.get("expression")
 130
 131    @property
 132    def expressions(self):
 133        """
 134        Retrieves the argument with key "expressions".
 135        """
 136        return self.args.get("expressions") or []
 137
 138    def text(self, key) -> str:
 139        """
 140        Returns a textual representation of the argument corresponding to "key". This can only be used
 141        for args that are strings or leaf Expression instances, such as identifiers and literals.
 142        """
 143        field = self.args.get(key)
 144        if isinstance(field, str):
 145            return field
 146        if isinstance(field, (Identifier, Literal, Var)):
 147            return field.this
 148        if isinstance(field, (Star, Null)):
 149            return field.name
 150        return ""
 151
 152    @property
 153    def is_string(self) -> bool:
 154        """
 155        Checks whether a Literal expression is a string.
 156        """
 157        return isinstance(self, Literal) and self.args["is_string"]
 158
 159    @property
 160    def is_number(self) -> bool:
 161        """
 162        Checks whether a Literal expression is a number.
 163        """
 164        return isinstance(self, Literal) and not self.args["is_string"]
 165
 166    @property
 167    def is_int(self) -> bool:
 168        """
 169        Checks whether a Literal expression is an integer.
 170        """
 171        if self.is_number:
 172            try:
 173                int(self.name)
 174                return True
 175            except ValueError:
 176                pass
 177        return False
 178
 179    @property
 180    def is_star(self) -> bool:
 181        """Checks whether an expression is a star."""
 182        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 183
 184    @property
 185    def alias(self) -> str:
 186        """
 187        Returns the alias of the expression, or an empty string if it's not aliased.
 188        """
 189        if isinstance(self.args.get("alias"), TableAlias):
 190            return self.args["alias"].name
 191        return self.text("alias")
 192
 193    @property
 194    def name(self) -> str:
 195        return self.text("this")
 196
 197    @property
 198    def alias_or_name(self) -> str:
 199        return self.alias or self.name
 200
 201    @property
 202    def output_name(self) -> str:
 203        """
 204        Name of the output column if this expression is a selection.
 205
 206        If the Expression has no output name, an empty string is returned.
 207
 208        Example:
 209            >>> from sqlglot import parse_one
 210            >>> parse_one("SELECT a").expressions[0].output_name
 211            'a'
 212            >>> parse_one("SELECT b AS c").expressions[0].output_name
 213            'c'
 214            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 215            ''
 216        """
 217        return ""
 218
 219    @property
 220    def type(self) -> t.Optional[DataType]:
 221        return self._type
 222
 223    @type.setter
 224    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 225        if dtype and not isinstance(dtype, DataType):
 226            dtype = DataType.build(dtype)
 227        self._type = dtype  # type: ignore
 228
 229    @property
 230    def meta(self) -> t.Dict[str, t.Any]:
 231        if self._meta is None:
 232            self._meta = {}
 233        return self._meta
 234
 235    def __deepcopy__(self, memo):
 236        copy = self.__class__(**deepcopy(self.args))
 237        if self.comments is not None:
 238            copy.comments = deepcopy(self.comments)
 239
 240        if self._type is not None:
 241            copy._type = self._type.copy()
 242
 243        if self._meta is not None:
 244            copy._meta = deepcopy(self._meta)
 245
 246        return copy
 247
 248    def copy(self):
 249        """
 250        Returns a deep copy of the expression.
 251        """
 252        new = deepcopy(self)
 253        new.parent = self.parent
 254        return new
 255
 256    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 257        if self.comments is None:
 258            self.comments = []
 259        if comments:
 260            self.comments.extend(comments)
 261
 262    def append(self, arg_key: str, value: t.Any) -> None:
 263        """
 264        Appends value to arg_key if it's a list or sets it as a new list.
 265
 266        Args:
 267            arg_key (str): name of the list expression arg
 268            value (Any): value to append to the list
 269        """
 270        if not isinstance(self.args.get(arg_key), list):
 271            self.args[arg_key] = []
 272        self.args[arg_key].append(value)
 273        self._set_parent(arg_key, value)
 274
 275    def set(self, arg_key: str, value: t.Any) -> None:
 276        """
 277        Sets arg_key to value.
 278
 279        Args:
 280            arg_key: name of the expression arg.
 281            value: value to set the arg to.
 282        """
 283        if value is None:
 284            self.args.pop(arg_key, None)
 285            return
 286
 287        self.args[arg_key] = value
 288        self._set_parent(arg_key, value)
 289
 290    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 291        if hasattr(value, "parent"):
 292            value.parent = self
 293            value.arg_key = arg_key
 294        elif type(value) is list:
 295            for v in value:
 296                if hasattr(v, "parent"):
 297                    v.parent = self
 298                    v.arg_key = arg_key
 299
 300    @property
 301    def depth(self) -> int:
 302        """
 303        Returns the depth of this tree.
 304        """
 305        if self.parent:
 306            return self.parent.depth + 1
 307        return 0
 308
 309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 310        """Yields the key and expression for all arguments, exploding list args."""
 311        for k, vs in self.args.items():
 312            if type(vs) is list:
 313                for v in vs:
 314                    if hasattr(v, "parent"):
 315                        yield k, v
 316            else:
 317                if hasattr(vs, "parent"):
 318                    yield k, vs
 319
 320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 321        """
 322        Returns the first node in this tree which matches at least one of
 323        the specified types.
 324
 325        Args:
 326            expression_types: the expression type(s) to match.
 327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 328
 329        Returns:
 330            The node which matches the criteria or None if no such node was found.
 331        """
 332        return next(self.find_all(*expression_types, bfs=bfs), None)
 333
 334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 335        """
 336        Returns a generator object which visits all nodes in this tree and only
 337        yields those that match at least one of the specified expression types.
 338
 339        Args:
 340            expression_types: the expression type(s) to match.
 341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 342
 343        Returns:
 344            The generator object.
 345        """
 346        for expression, *_ in self.walk(bfs=bfs):
 347            if isinstance(expression, expression_types):
 348                yield expression
 349
 350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 351        """
 352        Returns a nearest parent matching expression_types.
 353
 354        Args:
 355            expression_types: the expression type(s) to match.
 356
 357        Returns:
 358            The parent node.
 359        """
 360        ancestor = self.parent
 361        while ancestor and not isinstance(ancestor, expression_types):
 362            ancestor = ancestor.parent
 363        return t.cast(E, ancestor)
 364
 365    @property
 366    def parent_select(self) -> t.Optional[Select]:
 367        """
 368        Returns the parent select statement.
 369        """
 370        return self.find_ancestor(Select)
 371
 372    @property
 373    def same_parent(self) -> bool:
 374        """Returns if the parent is the same class as itself."""
 375        return type(self.parent) is self.__class__
 376
 377    def root(self) -> Expression:
 378        """
 379        Returns the root expression of this tree.
 380        """
 381        expression = self
 382        while expression.parent:
 383            expression = expression.parent
 384        return expression
 385
 386    def walk(self, bfs=True, prune=None):
 387        """
 388        Returns a generator object which visits all nodes in this tree.
 389
 390        Args:
 391            bfs (bool): if set to True the BFS traversal order will be applied,
 392                otherwise the DFS traversal will be used instead.
 393            prune ((node, parent, arg_key) -> bool): callable that returns True if
 394                the generator should stop traversing this branch of the tree.
 395
 396        Returns:
 397            the generator object.
 398        """
 399        if bfs:
 400            yield from self.bfs(prune=prune)
 401        else:
 402            yield from self.dfs(prune=prune)
 403
 404    def dfs(self, parent=None, key=None, prune=None):
 405        """
 406        Returns a generator object which visits all nodes in this tree in
 407        the DFS (Depth-first) order.
 408
 409        Returns:
 410            The generator object.
 411        """
 412        parent = parent or self.parent
 413        yield self, parent, key
 414        if prune and prune(self, parent, key):
 415            return
 416
 417        for k, v in self.iter_expressions():
 418            yield from v.dfs(self, k, prune)
 419
 420    def bfs(self, prune=None):
 421        """
 422        Returns a generator object which visits all nodes in this tree in
 423        the BFS (Breadth-first) order.
 424
 425        Returns:
 426            The generator object.
 427        """
 428        queue = deque([(self, self.parent, None)])
 429
 430        while queue:
 431            item, parent, key = queue.popleft()
 432
 433            yield item, parent, key
 434            if prune and prune(item, parent, key):
 435                continue
 436
 437            for k, v in item.iter_expressions():
 438                queue.append((v, item, k))
 439
 440    def unnest(self):
 441        """
 442        Returns the first non parenthesis child or self.
 443        """
 444        expression = self
 445        while type(expression) is Paren:
 446            expression = expression.this
 447        return expression
 448
 449    def unalias(self):
 450        """
 451        Returns the inner expression if this is an Alias.
 452        """
 453        if isinstance(self, Alias):
 454            return self.this
 455        return self
 456
 457    def unnest_operands(self):
 458        """
 459        Returns unnested operands as a tuple.
 460        """
 461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 462
 463    def flatten(self, unnest=True):
 464        """
 465        Returns a generator which yields child nodes who's parents are the same class.
 466
 467        A AND B AND C -> [A, B, C]
 468        """
 469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 470            if not type(node) is self.__class__:
 471                yield node.unnest() if unnest else node
 472
 473    def __str__(self) -> str:
 474        return self.sql()
 475
 476    def __repr__(self) -> str:
 477        return self._to_s()
 478
 479    def sql(self, dialect: DialectType = None, **opts) -> str:
 480        """
 481        Returns SQL string representation of this tree.
 482
 483        Args:
 484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 485            opts: other `sqlglot.generator.Generator` options.
 486
 487        Returns:
 488            The SQL string.
 489        """
 490        from sqlglot.dialects import Dialect
 491
 492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 493
 494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 495        indent = "" if not level else "\n"
 496        indent += "".join(["  "] * level)
 497        left = f"({self.key.upper()} "
 498
 499        args: t.Dict[str, t.Any] = {
 500            k: ", ".join(
 501                v._to_s(hide_missing=hide_missing, level=level + 1)
 502                if hasattr(v, "_to_s")
 503                else str(v)
 504                for v in ensure_list(vs)
 505                if v is not None
 506            )
 507            for k, vs in self.args.items()
 508        }
 509        args["comments"] = self.comments
 510        args["type"] = self.type
 511        args = {k: v for k, v in args.items() if v or not hide_missing}
 512
 513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 514        right += ")"
 515
 516        return indent + left + right
 517
 518    def transform(self, fun, *args, copy=True, **kwargs):
 519        """
 520        Recursively visits all tree nodes (excluding already transformed ones)
 521        and applies the given transformation function to each node.
 522
 523        Args:
 524            fun (function): a function which takes a node as an argument and returns a
 525                new transformed node or the same node without modifications. If the function
 526                returns None, then the corresponding node will be removed from the syntax tree.
 527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 528                modified in place.
 529
 530        Returns:
 531            The transformed tree.
 532        """
 533        node = self.copy() if copy else self
 534        new_node = fun(node, *args, **kwargs)
 535
 536        if new_node is None or not isinstance(new_node, Expression):
 537            return new_node
 538        if new_node is not node:
 539            new_node.parent = node.parent
 540            return new_node
 541
 542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 543        return new_node
 544
 545    @t.overload
 546    def replace(self, expression: E) -> E:
 547        ...
 548
 549    @t.overload
 550    def replace(self, expression: None) -> None:
 551        ...
 552
 553    def replace(self, expression):
 554        """
 555        Swap out this expression with a new expression.
 556
 557        For example::
 558
 559            >>> tree = Select().select("x").from_("tbl")
 560            >>> tree.find(Column).replace(Column(this="y"))
 561            (COLUMN this: y)
 562            >>> tree.sql()
 563            'SELECT y FROM tbl'
 564
 565        Args:
 566            expression: new node
 567
 568        Returns:
 569            The new expression or expressions.
 570        """
 571        if not self.parent:
 572            return expression
 573
 574        parent = self.parent
 575        self.parent = None
 576
 577        replace_children(parent, lambda child: expression if child is self else child)
 578        return expression
 579
 580    def pop(self: E) -> E:
 581        """
 582        Remove this expression from its AST.
 583
 584        Returns:
 585            The popped expression.
 586        """
 587        self.replace(None)
 588        return self
 589
 590    def assert_is(self, type_: t.Type[E]) -> E:
 591        """
 592        Assert that this `Expression` is an instance of `type_`.
 593
 594        If it is NOT an instance of `type_`, this raises an assertion error.
 595        Otherwise, this returns this expression.
 596
 597        Examples:
 598            This is useful for type security in chained expressions:
 599
 600            >>> import sqlglot
 601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 602            'SELECT x, z FROM y'
 603        """
 604        assert isinstance(self, type_)
 605        return self
 606
 607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 608        """
 609        Checks if this expression is valid (e.g. all mandatory args are set).
 610
 611        Args:
 612            args: a sequence of values that were used to instantiate a Func expression. This is used
 613                to check that the provided arguments don't exceed the function argument limit.
 614
 615        Returns:
 616            A list of error messages for all possible errors that were found.
 617        """
 618        errors: t.List[str] = []
 619
 620        for k in self.args:
 621            if k not in self.arg_types:
 622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 623        for k, mandatory in self.arg_types.items():
 624            v = self.args.get(k)
 625            if mandatory and (v is None or (isinstance(v, list) and not v)):
 626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 627
 628        if (
 629            args
 630            and isinstance(self, Func)
 631            and len(args) > len(self.arg_types)
 632            and not self.is_var_len_args
 633        ):
 634            errors.append(
 635                f"The number of provided arguments ({len(args)}) is greater than "
 636                f"the maximum number of supported arguments ({len(self.arg_types)})"
 637            )
 638
 639        return errors
 640
 641    def dump(self):
 642        """
 643        Dump this Expression to a JSON-serializable dict.
 644        """
 645        from sqlglot.serde import dump
 646
 647        return dump(self)
 648
 649    @classmethod
 650    def load(cls, obj):
 651        """
 652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 653        """
 654        from sqlglot.serde import load
 655
 656        return load(obj)
 657
 658
 659IntoType = t.Union[
 660    str,
 661    t.Type[Expression],
 662    t.Collection[t.Union[str, t.Type[Expression]]],
 663]
 664ExpOrStr = t.Union[str, Expression]
 665
 666
 667class Condition(Expression):
 668    def and_(
 669        self,
 670        *expressions: t.Optional[ExpOrStr],
 671        dialect: DialectType = None,
 672        copy: bool = True,
 673        **opts,
 674    ) -> Condition:
 675        """
 676        AND this condition with one or multiple expressions.
 677
 678        Example:
 679            >>> condition("x=1").and_("y=1").sql()
 680            'x = 1 AND y = 1'
 681
 682        Args:
 683            *expressions: the SQL code strings to parse.
 684                If an `Expression` instance is passed, it will be used as-is.
 685            dialect: the dialect used to parse the input expression.
 686            copy: whether or not to copy the involved expressions (only applies to Expressions).
 687            opts: other options to use to parse the input expressions.
 688
 689        Returns:
 690            The new And condition.
 691        """
 692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 693
 694    def or_(
 695        self,
 696        *expressions: t.Optional[ExpOrStr],
 697        dialect: DialectType = None,
 698        copy: bool = True,
 699        **opts,
 700    ) -> Condition:
 701        """
 702        OR this condition with one or multiple expressions.
 703
 704        Example:
 705            >>> condition("x=1").or_("y=1").sql()
 706            'x = 1 OR y = 1'
 707
 708        Args:
 709            *expressions: the SQL code strings to parse.
 710                If an `Expression` instance is passed, it will be used as-is.
 711            dialect: the dialect used to parse the input expression.
 712            copy: whether or not to copy the involved expressions (only applies to Expressions).
 713            opts: other options to use to parse the input expressions.
 714
 715        Returns:
 716            The new Or condition.
 717        """
 718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 719
 720    def not_(self, copy: bool = True):
 721        """
 722        Wrap this condition with NOT.
 723
 724        Example:
 725            >>> condition("x=1").not_().sql()
 726            'NOT x = 1'
 727
 728        Args:
 729            copy: whether or not to copy this object.
 730
 731        Returns:
 732            The new Not instance.
 733        """
 734        return not_(self, copy=copy)
 735
 736    def as_(
 737        self,
 738        alias: str | Identifier,
 739        quoted: t.Optional[bool] = None,
 740        dialect: DialectType = None,
 741        copy: bool = True,
 742        **opts,
 743    ) -> Alias:
 744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 745
 746    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 747        this = self.copy()
 748        other = convert(other, copy=True)
 749        if not isinstance(this, klass) and not isinstance(other, klass):
 750            this = _wrap(this, Binary)
 751            other = _wrap(other, Binary)
 752        if reverse:
 753            return klass(this=other, expression=this)
 754        return klass(this=this, expression=other)
 755
 756    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 757        return Bracket(
 758            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 759        )
 760
 761    def isin(
 762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
 763    ) -> In:
 764        return In(
 765            this=_maybe_copy(self, copy),
 766            expressions=[convert(e, copy=copy) for e in expressions],
 767            query=maybe_parse(query, copy=copy, **opts) if query else None,
 768        )
 769
 770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 771        return Between(
 772            this=_maybe_copy(self, copy),
 773            low=convert(low, copy=copy, **opts),
 774            high=convert(high, copy=copy, **opts),
 775        )
 776
 777    def is_(self, other: ExpOrStr) -> Is:
 778        return self._binop(Is, other)
 779
 780    def like(self, other: ExpOrStr) -> Like:
 781        return self._binop(Like, other)
 782
 783    def ilike(self, other: ExpOrStr) -> ILike:
 784        return self._binop(ILike, other)
 785
 786    def eq(self, other: t.Any) -> EQ:
 787        return self._binop(EQ, other)
 788
 789    def neq(self, other: t.Any) -> NEQ:
 790        return self._binop(NEQ, other)
 791
 792    def rlike(self, other: ExpOrStr) -> RegexpLike:
 793        return self._binop(RegexpLike, other)
 794
 795    def __lt__(self, other: t.Any) -> LT:
 796        return self._binop(LT, other)
 797
 798    def __le__(self, other: t.Any) -> LTE:
 799        return self._binop(LTE, other)
 800
 801    def __gt__(self, other: t.Any) -> GT:
 802        return self._binop(GT, other)
 803
 804    def __ge__(self, other: t.Any) -> GTE:
 805        return self._binop(GTE, other)
 806
 807    def __add__(self, other: t.Any) -> Add:
 808        return self._binop(Add, other)
 809
 810    def __radd__(self, other: t.Any) -> Add:
 811        return self._binop(Add, other, reverse=True)
 812
 813    def __sub__(self, other: t.Any) -> Sub:
 814        return self._binop(Sub, other)
 815
 816    def __rsub__(self, other: t.Any) -> Sub:
 817        return self._binop(Sub, other, reverse=True)
 818
 819    def __mul__(self, other: t.Any) -> Mul:
 820        return self._binop(Mul, other)
 821
 822    def __rmul__(self, other: t.Any) -> Mul:
 823        return self._binop(Mul, other, reverse=True)
 824
 825    def __truediv__(self, other: t.Any) -> Div:
 826        return self._binop(Div, other)
 827
 828    def __rtruediv__(self, other: t.Any) -> Div:
 829        return self._binop(Div, other, reverse=True)
 830
 831    def __floordiv__(self, other: t.Any) -> IntDiv:
 832        return self._binop(IntDiv, other)
 833
 834    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 835        return self._binop(IntDiv, other, reverse=True)
 836
 837    def __mod__(self, other: t.Any) -> Mod:
 838        return self._binop(Mod, other)
 839
 840    def __rmod__(self, other: t.Any) -> Mod:
 841        return self._binop(Mod, other, reverse=True)
 842
 843    def __pow__(self, other: t.Any) -> Pow:
 844        return self._binop(Pow, other)
 845
 846    def __rpow__(self, other: t.Any) -> Pow:
 847        return self._binop(Pow, other, reverse=True)
 848
 849    def __and__(self, other: t.Any) -> And:
 850        return self._binop(And, other)
 851
 852    def __rand__(self, other: t.Any) -> And:
 853        return self._binop(And, other, reverse=True)
 854
 855    def __or__(self, other: t.Any) -> Or:
 856        return self._binop(Or, other)
 857
 858    def __ror__(self, other: t.Any) -> Or:
 859        return self._binop(Or, other, reverse=True)
 860
 861    def __neg__(self) -> Neg:
 862        return Neg(this=_wrap(self.copy(), Binary))
 863
 864    def __invert__(self) -> Not:
 865        return not_(self.copy())
 866
 867
 868class Predicate(Condition):
 869    """Relationships like x = y, x > 1, x >= y."""
 870
 871
 872class DerivedTable(Expression):
 873    @property
 874    def alias_column_names(self) -> t.List[str]:
 875        table_alias = self.args.get("alias")
 876        if not table_alias:
 877            return []
 878        return [c.name for c in table_alias.args.get("columns") or []]
 879
 880    @property
 881    def selects(self):
 882        return self.this.selects if isinstance(self.this, Subqueryable) else []
 883
 884    @property
 885    def named_selects(self):
 886        return [select.output_name for select in self.selects]
 887
 888
 889class Unionable(Expression):
 890    def union(
 891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 892    ) -> Unionable:
 893        """
 894        Builds a UNION expression.
 895
 896        Example:
 897            >>> import sqlglot
 898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 899            'SELECT * FROM foo UNION SELECT * FROM bla'
 900
 901        Args:
 902            expression: the SQL code string.
 903                If an `Expression` instance is passed, it will be used as-is.
 904            distinct: set the DISTINCT flag if and only if this is true.
 905            dialect: the dialect used to parse the input expression.
 906            opts: other options to use to parse the input expressions.
 907
 908        Returns:
 909            The new Union expression.
 910        """
 911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 912
 913    def intersect(
 914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 915    ) -> Unionable:
 916        """
 917        Builds an INTERSECT expression.
 918
 919        Example:
 920            >>> import sqlglot
 921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 923
 924        Args:
 925            expression: the SQL code string.
 926                If an `Expression` instance is passed, it will be used as-is.
 927            distinct: set the DISTINCT flag if and only if this is true.
 928            dialect: the dialect used to parse the input expression.
 929            opts: other options to use to parse the input expressions.
 930
 931        Returns:
 932            The new Intersect expression.
 933        """
 934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 935
 936    def except_(
 937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 938    ) -> Unionable:
 939        """
 940        Builds an EXCEPT expression.
 941
 942        Example:
 943            >>> import sqlglot
 944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 946
 947        Args:
 948            expression: the SQL code string.
 949                If an `Expression` instance is passed, it will be used as-is.
 950            distinct: set the DISTINCT flag if and only if this is true.
 951            dialect: the dialect used to parse the input expression.
 952            opts: other options to use to parse the input expressions.
 953
 954        Returns:
 955            The new Except expression.
 956        """
 957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 958
 959
 960class UDTF(DerivedTable, Unionable):
 961    @property
 962    def selects(self):
 963        alias = self.args.get("alias")
 964        return alias.columns if alias else []
 965
 966
 967class Cache(Expression):
 968    arg_types = {
 969        "with": False,
 970        "this": True,
 971        "lazy": False,
 972        "options": False,
 973        "expression": False,
 974    }
 975
 976
 977class Uncache(Expression):
 978    arg_types = {"this": True, "exists": False}
 979
 980
 981class Create(Expression):
 982    arg_types = {
 983        "with": False,
 984        "this": True,
 985        "kind": True,
 986        "expression": False,
 987        "exists": False,
 988        "properties": False,
 989        "replace": False,
 990        "unique": False,
 991        "indexes": False,
 992        "no_schema_binding": False,
 993        "begin": False,
 994        "clone": False,
 995    }
 996
 997
 998# https://docs.snowflake.com/en/sql-reference/sql/create-clone
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
1006
1007
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
1010
1011
1012class Pragma(Expression):
1013    pass
1014
1015
1016class Set(Expression):
1017    arg_types = {"expressions": False, "unset": False, "tag": False}
1018
1019
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
1028
1029
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
1048
1049
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
1052
1053
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
1056
1057
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
1064
1065
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
1068
1069
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
1072
1073
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
1080
1081
1082class BitString(Condition):
1083    pass
1084
1085
1086class HexString(Condition):
1087    pass
1088
1089
1090class ByteString(Condition):
1091    pass
1092
1093
1094class RawString(Condition):
1095    pass
1096
1097
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)
1137
1138
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
1141
1142
1143class ColumnDef(Expression):
1144    arg_types = {
1145        "this": True,
1146        "kind": False,
1147        "constraints": False,
1148        "exists": False,
1149        "position": False,
1150    }
1151
1152    @property
1153    def constraints(self) -> t.List[ColumnConstraint]:
1154        return self.args.get("constraints") or []
1155
1156
1157class AlterColumn(Expression):
1158    arg_types = {
1159        "this": True,
1160        "dtype": False,
1161        "collate": False,
1162        "using": False,
1163        "default": False,
1164        "drop": False,
1165    }
1166
1167
1168class RenameTable(Expression):
1169    pass
1170
1171
1172class Comment(Expression):
1173    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1174
1175
1176# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1177class MergeTreeTTLAction(Expression):
1178    arg_types = {
1179        "this": True,
1180        "delete": False,
1181        "recompress": False,
1182        "to_disk": False,
1183        "to_volume": False,
1184    }
1185
1186
1187# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1188class MergeTreeTTL(Expression):
1189    arg_types = {
1190        "expressions": True,
1191        "where": False,
1192        "group": False,
1193        "aggregates": False,
1194    }
1195
1196
1197class ColumnConstraint(Expression):
1198    arg_types = {"this": False, "kind": True}
1199
1200    @property
1201    def kind(self) -> ColumnConstraintKind:
1202        return self.args["kind"]
1203
1204
1205class ColumnConstraintKind(Expression):
1206    pass
1207
1208
1209class AutoIncrementColumnConstraint(ColumnConstraintKind):
1210    pass
1211
1212
1213class CaseSpecificColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"not_": True}
1215
1216
1217class CharacterSetColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"this": True}
1219
1220
1221class CheckColumnConstraint(ColumnConstraintKind):
1222    pass
1223
1224
1225class CollateColumnConstraint(ColumnConstraintKind):
1226    pass
1227
1228
1229class CommentColumnConstraint(ColumnConstraintKind):
1230    pass
1231
1232
1233class CompressColumnConstraint(ColumnConstraintKind):
1234    pass
1235
1236
1237class DateFormatColumnConstraint(ColumnConstraintKind):
1238    arg_types = {"this": True}
1239
1240
1241class DefaultColumnConstraint(ColumnConstraintKind):
1242    pass
1243
1244
1245class EncodeColumnConstraint(ColumnConstraintKind):
1246    pass
1247
1248
1249class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1250    # this: True -> ALWAYS, this: False -> BY DEFAULT
1251    arg_types = {
1252        "this": False,
1253        "expression": False,
1254        "on_null": False,
1255        "start": False,
1256        "increment": False,
1257        "minvalue": False,
1258        "maxvalue": False,
1259        "cycle": False,
1260    }
1261
1262
1263class InlineLengthColumnConstraint(ColumnConstraintKind):
1264    pass
1265
1266
1267class NotNullColumnConstraint(ColumnConstraintKind):
1268    arg_types = {"allow_null": False}
1269
1270
1271# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1272class OnUpdateColumnConstraint(ColumnConstraintKind):
1273    pass
1274
1275
1276class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1277    arg_types = {"desc": False}
1278
1279
1280class TitleColumnConstraint(ColumnConstraintKind):
1281    pass
1282
1283
1284class UniqueColumnConstraint(ColumnConstraintKind):
1285    arg_types = {"this": False}
1286
1287
1288class UppercaseColumnConstraint(ColumnConstraintKind):
1289    arg_types: t.Dict[str, t.Any] = {}
1290
1291
1292class PathColumnConstraint(ColumnConstraintKind):
1293    pass
1294
1295
1296class Constraint(Expression):
1297    arg_types = {"this": True, "expressions": True}
1298
1299
1300class Delete(Expression):
1301    arg_types = {
1302        "with": False,
1303        "this": False,
1304        "using": False,
1305        "where": False,
1306        "returning": False,
1307        "limit": False,
1308        "tables": False,  # Multiple-Table Syntax (MySQL)
1309    }
1310
1311    def delete(
1312        self,
1313        table: ExpOrStr,
1314        dialect: DialectType = None,
1315        copy: bool = True,
1316        **opts,
1317    ) -> Delete:
1318        """
1319        Create a DELETE expression or replace the table on an existing DELETE expression.
1320
1321        Example:
1322            >>> delete("tbl").sql()
1323            'DELETE FROM tbl'
1324
1325        Args:
1326            table: the table from which to delete.
1327            dialect: the dialect used to parse the input expression.
1328            copy: if `False`, modify this expression instance in-place.
1329            opts: other options to use to parse the input expressions.
1330
1331        Returns:
1332            Delete: the modified expression.
1333        """
1334        return _apply_builder(
1335            expression=table,
1336            instance=self,
1337            arg="this",
1338            dialect=dialect,
1339            into=Table,
1340            copy=copy,
1341            **opts,
1342        )
1343
1344    def where(
1345        self,
1346        *expressions: t.Optional[ExpOrStr],
1347        append: bool = True,
1348        dialect: DialectType = None,
1349        copy: bool = True,
1350        **opts,
1351    ) -> Delete:
1352        """
1353        Append to or set the WHERE expressions.
1354
1355        Example:
1356            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1357            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1358
1359        Args:
1360            *expressions: the SQL code strings to parse.
1361                If an `Expression` instance is passed, it will be used as-is.
1362                Multiple expressions are combined with an AND operator.
1363            append: if `True`, AND the new expressions to any existing expression.
1364                Otherwise, this resets the expression.
1365            dialect: the dialect used to parse the input expressions.
1366            copy: if `False`, modify this expression instance in-place.
1367            opts: other options to use to parse the input expressions.
1368
1369        Returns:
1370            Delete: the modified expression.
1371        """
1372        return _apply_conjunction_builder(
1373            *expressions,
1374            instance=self,
1375            arg="where",
1376            append=append,
1377            into=Where,
1378            dialect=dialect,
1379            copy=copy,
1380            **opts,
1381        )
1382
1383    def returning(
1384        self,
1385        expression: ExpOrStr,
1386        dialect: DialectType = None,
1387        copy: bool = True,
1388        **opts,
1389    ) -> Delete:
1390        """
1391        Set the RETURNING expression. Not supported by all dialects.
1392
1393        Example:
1394            >>> delete("tbl").returning("*", dialect="postgres").sql()
1395            'DELETE FROM tbl RETURNING *'
1396
1397        Args:
1398            expression: the SQL code strings to parse.
1399                If an `Expression` instance is passed, it will be used as-is.
1400            dialect: the dialect used to parse the input expressions.
1401            copy: if `False`, modify this expression instance in-place.
1402            opts: other options to use to parse the input expressions.
1403
1404        Returns:
1405            Delete: the modified expression.
1406        """
1407        return _apply_builder(
1408            expression=expression,
1409            instance=self,
1410            arg="returning",
1411            prefix="RETURNING",
1412            dialect=dialect,
1413            copy=copy,
1414            into=Returning,
1415            **opts,
1416        )
1417
1418
1419class Drop(Expression):
1420    arg_types = {
1421        "this": False,
1422        "kind": False,
1423        "exists": False,
1424        "temporary": False,
1425        "materialized": False,
1426        "cascade": False,
1427        "constraints": False,
1428        "purge": False,
1429    }
1430
1431
1432class Filter(Expression):
1433    arg_types = {"this": True, "expression": True}
1434
1435
1436class Check(Expression):
1437    pass
1438
1439
1440class Directory(Expression):
1441    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1442    arg_types = {"this": True, "local": False, "row_format": False}
1443
1444
1445class ForeignKey(Expression):
1446    arg_types = {
1447        "expressions": True,
1448        "reference": False,
1449        "delete": False,
1450        "update": False,
1451    }
1452
1453
1454class PrimaryKey(Expression):
1455    arg_types = {"expressions": True, "options": False}
1456
1457
1458# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1459# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1460class Into(Expression):
1461    arg_types = {"this": True, "temporary": False, "unlogged": False}
1462
1463
1464class From(Expression):
1465    @property
1466    def name(self) -> str:
1467        return self.this.name
1468
1469    @property
1470    def alias_or_name(self) -> str:
1471        return self.this.alias_or_name
1472
1473
1474class Having(Expression):
1475    pass
1476
1477
1478class Hint(Expression):
1479    arg_types = {"expressions": True}
1480
1481
1482class JoinHint(Expression):
1483    arg_types = {"this": True, "expressions": True}
1484
1485
1486class Identifier(Expression):
1487    arg_types = {"this": True, "quoted": False}
1488
1489    @property
1490    def quoted(self) -> bool:
1491        return bool(self.args.get("quoted"))
1492
1493    @property
1494    def hashable_args(self) -> t.Any:
1495        return (self.this, self.quoted)
1496
1497    @property
1498    def output_name(self) -> str:
1499        return self.name
1500
1501
1502class Index(Expression):
1503    arg_types = {
1504        "this": False,
1505        "table": False,
1506        "using": False,
1507        "where": False,
1508        "columns": False,
1509        "unique": False,
1510        "primary": False,
1511        "amp": False,  # teradata
1512        "partition_by": False,  # teradata
1513    }
1514
1515
1516class Insert(Expression):
1517    arg_types = {
1518        "with": False,
1519        "this": True,
1520        "expression": False,
1521        "conflict": False,
1522        "returning": False,
1523        "overwrite": False,
1524        "exists": False,
1525        "partition": False,
1526        "alternative": False,
1527        "where": False,
1528        "ignore": False,
1529    }
1530
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )
1566
1567
1568class OnConflict(Expression):
1569    arg_types = {
1570        "duplicate": False,
1571        "expressions": False,
1572        "nothing": False,
1573        "key": False,
1574        "constraint": False,
1575    }
1576
1577
1578class Returning(Expression):
1579    arg_types = {"expressions": True}
1580
1581
1582# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1583class Introducer(Expression):
1584    arg_types = {"this": True, "expression": True}
1585
1586
1587# national char, like n'utf8'
1588class National(Expression):
1589    pass
1590
1591
1592class LoadData(Expression):
1593    arg_types = {
1594        "this": True,
1595        "local": False,
1596        "overwrite": False,
1597        "inpath": True,
1598        "partition": False,
1599        "input_format": False,
1600        "serde": False,
1601    }
1602
1603
1604class Partition(Expression):
1605    arg_types = {"expressions": True}
1606
1607
1608class Fetch(Expression):
1609    arg_types = {
1610        "direction": False,
1611        "count": False,
1612        "percent": False,
1613        "with_ties": False,
1614    }
1615
1616
1617class Group(Expression):
1618    arg_types = {
1619        "expressions": False,
1620        "grouping_sets": False,
1621        "cube": False,
1622        "rollup": False,
1623        "totals": False,
1624        "all": False,
1625    }
1626
1627
1628class Lambda(Expression):
1629    arg_types = {"this": True, "expressions": True}
1630
1631
1632class Limit(Expression):
1633    arg_types = {"this": False, "expression": True, "offset": False}
1634
1635
1636class Literal(Condition):
1637    arg_types = {"this": True, "is_string": True}
1638
1639    @property
1640    def hashable_args(self) -> t.Any:
1641        return (self.this, self.args.get("is_string"))
1642
1643    @classmethod
1644    def number(cls, number) -> Literal:
1645        return cls(this=str(number), is_string=False)
1646
1647    @classmethod
1648    def string(cls, string) -> Literal:
1649        return cls(this=str(string), is_string=True)
1650
1651    @property
1652    def output_name(self) -> str:
1653        return self.name
1654
1655
1656class Join(Expression):
1657    arg_types = {
1658        "this": True,
1659        "on": False,
1660        "side": False,
1661        "kind": False,
1662        "using": False,
1663        "method": False,
1664        "global": False,
1665        "hint": False,
1666    }
1667
1668    @property
1669    def method(self) -> str:
1670        return self.text("method").upper()
1671
1672    @property
1673    def kind(self) -> str:
1674        return self.text("kind").upper()
1675
1676    @property
1677    def side(self) -> str:
1678        return self.text("side").upper()
1679
1680    @property
1681    def hint(self) -> str:
1682        return self.text("hint").upper()
1683
1684    @property
1685    def alias_or_name(self) -> str:
1686        return self.this.alias_or_name
1687
1688    def on(
1689        self,
1690        *expressions: t.Optional[ExpOrStr],
1691        append: bool = True,
1692        dialect: DialectType = None,
1693        copy: bool = True,
1694        **opts,
1695    ) -> Join:
1696        """
1697        Append to or set the ON expressions.
1698
1699        Example:
1700            >>> import sqlglot
1701            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1702            'JOIN x ON y = 1'
1703
1704        Args:
1705            *expressions: the SQL code strings to parse.
1706                If an `Expression` instance is passed, it will be used as-is.
1707                Multiple expressions are combined with an AND operator.
1708            append: if `True`, AND the new expressions to any existing expression.
1709                Otherwise, this resets the expression.
1710            dialect: the dialect used to parse the input expressions.
1711            copy: if `False`, modify this expression instance in-place.
1712            opts: other options to use to parse the input expressions.
1713
1714        Returns:
1715            The modified Join expression.
1716        """
1717        join = _apply_conjunction_builder(
1718            *expressions,
1719            instance=self,
1720            arg="on",
1721            append=append,
1722            dialect=dialect,
1723            copy=copy,
1724            **opts,
1725        )
1726
1727        if join.kind == "CROSS":
1728            join.set("kind", None)
1729
1730        return join
1731
1732    def using(
1733        self,
1734        *expressions: t.Optional[ExpOrStr],
1735        append: bool = True,
1736        dialect: DialectType = None,
1737        copy: bool = True,
1738        **opts,
1739    ) -> Join:
1740        """
1741        Append to or set the USING expressions.
1742
1743        Example:
1744            >>> import sqlglot
1745            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1746            'JOIN x USING (foo, bla)'
1747
1748        Args:
1749            *expressions: the SQL code strings to parse.
1750                If an `Expression` instance is passed, it will be used as-is.
1751            append: if `True`, concatenate the new expressions to the existing "using" list.
1752                Otherwise, this resets the expression.
1753            dialect: the dialect used to parse the input expressions.
1754            copy: if `False`, modify this expression instance in-place.
1755            opts: other options to use to parse the input expressions.
1756
1757        Returns:
1758            The modified Join expression.
1759        """
1760        join = _apply_list_builder(
1761            *expressions,
1762            instance=self,
1763            arg="using",
1764            append=append,
1765            dialect=dialect,
1766            copy=copy,
1767            **opts,
1768        )
1769
1770        if join.kind == "CROSS":
1771            join.set("kind", None)
1772
1773        return join
1774
1775
1776class Lateral(UDTF):
1777    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1778
1779
1780class MatchRecognize(Expression):
1781    arg_types = {
1782        "partition_by": False,
1783        "order": False,
1784        "measures": False,
1785        "rows": False,
1786        "after": False,
1787        "pattern": False,
1788        "define": False,
1789        "alias": False,
1790    }
1791
1792
1793# Clickhouse FROM FINAL modifier
1794# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1795class Final(Expression):
1796    pass
1797
1798
1799class Offset(Expression):
1800    arg_types = {"this": False, "expression": True}
1801
1802
1803class Order(Expression):
1804    arg_types = {"this": False, "expressions": True}
1805
1806
1807# hive specific sorts
1808# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1809class Cluster(Order):
1810    pass
1811
1812
1813class Distribute(Order):
1814    pass
1815
1816
1817class Sort(Order):
1818    pass
1819
1820
1821class Ordered(Expression):
1822    arg_types = {"this": True, "desc": True, "nulls_first": True}
1823
1824
1825class Property(Expression):
1826    arg_types = {"this": True, "value": True}
1827
1828
1829class AlgorithmProperty(Property):
1830    arg_types = {"this": True}
1831
1832
1833class AutoIncrementProperty(Property):
1834    arg_types = {"this": True}
1835
1836
1837class BlockCompressionProperty(Property):
1838    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1839
1840
1841class CharacterSetProperty(Property):
1842    arg_types = {"this": True, "default": True}
1843
1844
1845class ChecksumProperty(Property):
1846    arg_types = {"on": False, "default": False}
1847
1848
1849class CollateProperty(Property):
1850    arg_types = {"this": True}
1851
1852
1853class CopyGrantsProperty(Property):
1854    arg_types = {}
1855
1856
1857class DataBlocksizeProperty(Property):
1858    arg_types = {
1859        "size": False,
1860        "units": False,
1861        "minimum": False,
1862        "maximum": False,
1863        "default": False,
1864    }
1865
1866
1867class DefinerProperty(Property):
1868    arg_types = {"this": True}
1869
1870
1871class DistKeyProperty(Property):
1872    arg_types = {"this": True}
1873
1874
1875class DistStyleProperty(Property):
1876    arg_types = {"this": True}
1877
1878
1879class EngineProperty(Property):
1880    arg_types = {"this": True}
1881
1882
1883class ToTableProperty(Property):
1884    arg_types = {"this": True}
1885
1886
1887class ExecuteAsProperty(Property):
1888    arg_types = {"this": True}
1889
1890
1891class ExternalProperty(Property):
1892    arg_types = {"this": False}
1893
1894
1895class FallbackProperty(Property):
1896    arg_types = {"no": True, "protection": False}
1897
1898
1899class FileFormatProperty(Property):
1900    arg_types = {"this": True}
1901
1902
1903class FreespaceProperty(Property):
1904    arg_types = {"this": True, "percent": False}
1905
1906
1907class InputOutputFormat(Expression):
1908    arg_types = {"input_format": False, "output_format": False}
1909
1910
1911class IsolatedLoadingProperty(Property):
1912    arg_types = {
1913        "no": True,
1914        "concurrent": True,
1915        "for_all": True,
1916        "for_insert": True,
1917        "for_none": True,
1918    }
1919
1920
1921class JournalProperty(Property):
1922    arg_types = {
1923        "no": False,
1924        "dual": False,
1925        "before": False,
1926        "local": False,
1927        "after": False,
1928    }
1929
1930
1931class LanguageProperty(Property):
1932    arg_types = {"this": True}
1933
1934
1935# spark ddl
1936class ClusteredByProperty(Property):
1937    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
1938
1939
1940class DictProperty(Property):
1941    arg_types = {"this": True, "kind": True, "settings": False}
1942
1943
1944class DictSubProperty(Property):
1945    pass
1946
1947
1948class DictRange(Property):
1949    arg_types = {"this": True, "min": True, "max": True}
1950
1951
1952# Clickhouse CREATE ... ON CLUSTER modifier
1953# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
1954class OnCluster(Property):
1955    arg_types = {"this": True}
1956
1957
1958class LikeProperty(Property):
1959    arg_types = {"this": True, "expressions": False}
1960
1961
1962class LocationProperty(Property):
1963    arg_types = {"this": True}
1964
1965
1966class LockingProperty(Property):
1967    arg_types = {
1968        "this": False,
1969        "kind": True,
1970        "for_or_in": True,
1971        "lock_type": True,
1972        "override": False,
1973    }
1974
1975
1976class LogProperty(Property):
1977    arg_types = {"no": True}
1978
1979
1980class MaterializedProperty(Property):
1981    arg_types = {"this": False}
1982
1983
1984class MergeBlockRatioProperty(Property):
1985    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1986
1987
1988class NoPrimaryIndexProperty(Property):
1989    arg_types = {}
1990
1991
1992class OnCommitProperty(Property):
1993    arg_type = {"delete": False}
1994
1995
1996class PartitionedByProperty(Property):
1997    arg_types = {"this": True}
1998
1999
2000class ReturnsProperty(Property):
2001    arg_types = {"this": True, "is_table": False, "table": False}
2002
2003
2004class RowFormatProperty(Property):
2005    arg_types = {"this": True}
2006
2007
2008class RowFormatDelimitedProperty(Property):
2009    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2010    arg_types = {
2011        "fields": False,
2012        "escaped": False,
2013        "collection_items": False,
2014        "map_keys": False,
2015        "lines": False,
2016        "null": False,
2017        "serde": False,
2018    }
2019
2020
2021class RowFormatSerdeProperty(Property):
2022    arg_types = {"this": True}
2023
2024
2025class SchemaCommentProperty(Property):
2026    arg_types = {"this": True}
2027
2028
2029class SerdeProperties(Property):
2030    arg_types = {"expressions": True}
2031
2032
2033class SetProperty(Property):
2034    arg_types = {"multi": True}
2035
2036
2037class SettingsProperty(Property):
2038    arg_types = {"expressions": True}
2039
2040
2041class SortKeyProperty(Property):
2042    arg_types = {"this": True, "compound": False}
2043
2044
2045class SqlSecurityProperty(Property):
2046    arg_types = {"definer": True}
2047
2048
2049class StabilityProperty(Property):
2050    arg_types = {"this": True}
2051
2052
2053class TemporaryProperty(Property):
2054    arg_types = {}
2055
2056
2057class TransientProperty(Property):
2058    arg_types = {"this": False}
2059
2060
2061class VolatileProperty(Property):
2062    arg_types = {"this": False}
2063
2064
2065class WithDataProperty(Property):
2066    arg_types = {"no": True, "statistics": False}
2067
2068
2069class WithJournalTableProperty(Property):
2070    arg_types = {"this": True}
2071
2072
2073class Properties(Expression):
2074    arg_types = {"expressions": True}
2075
2076    NAME_TO_PROPERTY = {
2077        "ALGORITHM": AlgorithmProperty,
2078        "AUTO_INCREMENT": AutoIncrementProperty,
2079        "CHARACTER SET": CharacterSetProperty,
2080        "CLUSTERED_BY": ClusteredByProperty,
2081        "COLLATE": CollateProperty,
2082        "COMMENT": SchemaCommentProperty,
2083        "DEFINER": DefinerProperty,
2084        "DISTKEY": DistKeyProperty,
2085        "DISTSTYLE": DistStyleProperty,
2086        "ENGINE": EngineProperty,
2087        "EXECUTE AS": ExecuteAsProperty,
2088        "FORMAT": FileFormatProperty,
2089        "LANGUAGE": LanguageProperty,
2090        "LOCATION": LocationProperty,
2091        "PARTITIONED_BY": PartitionedByProperty,
2092        "RETURNS": ReturnsProperty,
2093        "ROW_FORMAT": RowFormatProperty,
2094        "SORTKEY": SortKeyProperty,
2095    }
2096
2097    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2098
2099    # CREATE property locations
2100    # Form: schema specified
2101    #   create [POST_CREATE]
2102    #     table a [POST_NAME]
2103    #     (b int) [POST_SCHEMA]
2104    #     with ([POST_WITH])
2105    #     index (b) [POST_INDEX]
2106    #
2107    # Form: alias selection
2108    #   create [POST_CREATE]
2109    #     table a [POST_NAME]
2110    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2111    #     index (c) [POST_INDEX]
2112    class Location(AutoName):
2113        POST_CREATE = auto()
2114        POST_NAME = auto()
2115        POST_SCHEMA = auto()
2116        POST_WITH = auto()
2117        POST_ALIAS = auto()
2118        POST_EXPRESSION = auto()
2119        POST_INDEX = auto()
2120        UNSUPPORTED = auto()
2121
2122    @classmethod
2123    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2124        expressions = []
2125        for key, value in properties_dict.items():
2126            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2127            if property_cls:
2128                expressions.append(property_cls(this=convert(value)))
2129            else:
2130                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2131
2132        return cls(expressions=expressions)
2133
2134
2135class Qualify(Expression):
2136    pass
2137
2138
2139# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2140class Return(Expression):
2141    pass
2142
2143
2144class Reference(Expression):
2145    arg_types = {"this": True, "expressions": False, "options": False}
2146
2147
2148class Tuple(Expression):
2149    arg_types = {"expressions": False}
2150
2151    def isin(
2152        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2153    ) -> In:
2154        return In(
2155            this=_maybe_copy(self, copy),
2156            expressions=[convert(e, copy=copy) for e in expressions],
2157            query=maybe_parse(query, copy=copy, **opts) if query else None,
2158        )
2159
2160
2161class Subqueryable(Unionable):
2162    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2163        """
2164        Convert this expression to an aliased expression that can be used as a Subquery.
2165
2166        Example:
2167            >>> subquery = Select().select("x").from_("tbl").subquery()
2168            >>> Select().select("x").from_(subquery).sql()
2169            'SELECT x FROM (SELECT x FROM tbl)'
2170
2171        Args:
2172            alias (str | Identifier): an optional alias for the subquery
2173            copy (bool): if `False`, modify this expression instance in-place.
2174
2175        Returns:
2176            Alias: the subquery
2177        """
2178        instance = _maybe_copy(self, copy)
2179        if not isinstance(alias, Expression):
2180            alias = TableAlias(this=to_identifier(alias)) if alias else None
2181
2182        return Subquery(this=instance, alias=alias)
2183
2184    def limit(
2185        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2186    ) -> Select:
2187        raise NotImplementedError
2188
2189    @property
2190    def ctes(self):
2191        with_ = self.args.get("with")
2192        if not with_:
2193            return []
2194        return with_.expressions
2195
2196    @property
2197    def selects(self):
2198        raise NotImplementedError("Subqueryable objects must implement `selects`")
2199
2200    @property
2201    def named_selects(self):
2202        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2203
2204    def with_(
2205        self,
2206        alias: ExpOrStr,
2207        as_: ExpOrStr,
2208        recursive: t.Optional[bool] = None,
2209        append: bool = True,
2210        dialect: DialectType = None,
2211        copy: bool = True,
2212        **opts,
2213    ) -> Subqueryable:
2214        """
2215        Append to or set the common table expressions.
2216
2217        Example:
2218            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2219            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2220
2221        Args:
2222            alias: the SQL code string to parse as the table name.
2223                If an `Expression` instance is passed, this is used as-is.
2224            as_: the SQL code string to parse as the table expression.
2225                If an `Expression` instance is passed, it will be used as-is.
2226            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2227            append: if `True`, add to any existing expressions.
2228                Otherwise, this resets the expressions.
2229            dialect: the dialect used to parse the input expression.
2230            copy: if `False`, modify this expression instance in-place.
2231            opts: other options to use to parse the input expressions.
2232
2233        Returns:
2234            The modified expression.
2235        """
2236        return _apply_cte_builder(
2237            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2238        )
2239
2240
2241QUERY_MODIFIERS = {
2242    "match": False,
2243    "laterals": False,
2244    "joins": False,
2245    "pivots": False,
2246    "where": False,
2247    "group": False,
2248    "having": False,
2249    "qualify": False,
2250    "windows": False,
2251    "distribute": False,
2252    "sort": False,
2253    "cluster": False,
2254    "order": False,
2255    "limit": False,
2256    "offset": False,
2257    "locks": False,
2258    "sample": False,
2259    "settings": False,
2260    "format": False,
2261}
2262
2263
2264# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2265class WithTableHint(Expression):
2266    arg_types = {"expressions": True}
2267
2268
2269# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2270class IndexTableHint(Expression):
2271    arg_types = {"this": True, "expressions": False, "target": False}
2272
2273
2274class Table(Expression):
2275    arg_types = {
2276        "this": True,
2277        "alias": False,
2278        "db": False,
2279        "catalog": False,
2280        "laterals": False,
2281        "joins": False,
2282        "pivots": False,
2283        "hints": False,
2284        "system_time": False,
2285        "wrapped": False,
2286    }
2287
2288    @property
2289    def name(self) -> str:
2290        if isinstance(self.this, Func):
2291            return ""
2292        return self.this.name
2293
2294    @property
2295    def db(self) -> str:
2296        return self.text("db")
2297
2298    @property
2299    def catalog(self) -> str:
2300        return self.text("catalog")
2301
2302    @property
2303    def parts(self) -> t.List[Identifier]:
2304        """Return the parts of a table in order catalog, db, table."""
2305        return [
2306            t.cast(Identifier, self.args[part])
2307            for part in ("catalog", "db", "this")
2308            if self.args.get(part)
2309        ]
2310
2311
2312# See the TSQL "Querying data in a system-versioned temporal table" page
2313class SystemTime(Expression):
2314    arg_types = {
2315        "this": False,
2316        "expression": False,
2317        "kind": True,
2318    }
2319
2320
2321class Union(Subqueryable):
2322    arg_types = {
2323        "with": False,
2324        "this": True,
2325        "expression": True,
2326        "distinct": False,
2327        **QUERY_MODIFIERS,
2328    }
2329
2330    def limit(
2331        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2332    ) -> Select:
2333        """
2334        Set the LIMIT expression.
2335
2336        Example:
2337            >>> select("1").union(select("1")).limit(1).sql()
2338            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2339
2340        Args:
2341            expression: the SQL code string to parse.
2342                This can also be an integer.
2343                If a `Limit` instance is passed, this is used as-is.
2344                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2345            dialect: the dialect used to parse the input expression.
2346            copy: if `False`, modify this expression instance in-place.
2347            opts: other options to use to parse the input expressions.
2348
2349        Returns:
2350            The limited subqueryable.
2351        """
2352        return (
2353            select("*")
2354            .from_(self.subquery(alias="_l_0", copy=copy))
2355            .limit(expression, dialect=dialect, copy=False, **opts)
2356        )
2357
2358    def select(
2359        self,
2360        *expressions: t.Optional[ExpOrStr],
2361        append: bool = True,
2362        dialect: DialectType = None,
2363        copy: bool = True,
2364        **opts,
2365    ) -> Union:
2366        """Append to or set the SELECT of the union recursively.
2367
2368        Example:
2369            >>> from sqlglot import parse_one
2370            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2371            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2372
2373        Args:
2374            *expressions: the SQL code strings to parse.
2375                If an `Expression` instance is passed, it will be used as-is.
2376            append: if `True`, add to any existing expressions.
2377                Otherwise, this resets the expressions.
2378            dialect: the dialect used to parse the input expressions.
2379            copy: if `False`, modify this expression instance in-place.
2380            opts: other options to use to parse the input expressions.
2381
2382        Returns:
2383            Union: the modified expression.
2384        """
2385        this = self.copy() if copy else self
2386        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2387        this.expression.unnest().select(
2388            *expressions, append=append, dialect=dialect, copy=False, **opts
2389        )
2390        return this
2391
2392    @property
2393    def named_selects(self):
2394        return self.this.unnest().named_selects
2395
2396    @property
2397    def is_star(self) -> bool:
2398        return self.this.is_star or self.expression.is_star
2399
2400    @property
2401    def selects(self):
2402        return self.this.unnest().selects
2403
2404    @property
2405    def left(self):
2406        return self.this
2407
2408    @property
2409    def right(self):
2410        return self.expression
2411
2412
2413class Except(Union):
2414    pass
2415
2416
2417class Intersect(Union):
2418    pass
2419
2420
2421class Unnest(UDTF):
2422    arg_types = {
2423        "expressions": True,
2424        "ordinality": False,
2425        "alias": False,
2426        "offset": False,
2427    }
2428
2429
2430class Update(Expression):
2431    arg_types = {
2432        "with": False,
2433        "this": False,
2434        "expressions": True,
2435        "from": False,
2436        "where": False,
2437        "returning": False,
2438        "limit": False,
2439    }
2440
2441
2442class Values(UDTF):
2443    arg_types = {
2444        "expressions": True,
2445        "ordinality": False,
2446        "alias": False,
2447    }
2448
2449
2450class Var(Expression):
2451    pass
2452
2453
2454class Schema(Expression):
2455    arg_types = {"this": False, "expressions": False}
2456
2457
2458# https://dev.mysql.com/doc/refman/8.0/en/select.html
2459# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2460class Lock(Expression):
2461    arg_types = {"update": True, "expressions": False, "wait": False}
2462
2463
2464class Select(Subqueryable):
2465    arg_types = {
2466        "with": False,
2467        "kind": False,
2468        "expressions": False,
2469        "hint": False,
2470        "distinct": False,
2471        "into": False,
2472        "from": False,
2473        **QUERY_MODIFIERS,
2474    }
2475
2476    def from_(
2477        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2478    ) -> Select:
2479        """
2480        Set the FROM expression.
2481
2482        Example:
2483            >>> Select().from_("tbl").select("x").sql()
2484            'SELECT x FROM tbl'
2485
2486        Args:
2487            expression : the SQL code strings to parse.
2488                If a `From` instance is passed, this is used as-is.
2489                If another `Expression` instance is passed, it will be wrapped in a `From`.
2490            dialect: the dialect used to parse the input expression.
2491            copy: if `False`, modify this expression instance in-place.
2492            opts: other options to use to parse the input expressions.
2493
2494        Returns:
2495            The modified Select expression.
2496        """
2497        return _apply_builder(
2498            expression=expression,
2499            instance=self,
2500            arg="from",
2501            into=From,
2502            prefix="FROM",
2503            dialect=dialect,
2504            copy=copy,
2505            **opts,
2506        )
2507
2508    def group_by(
2509        self,
2510        *expressions: t.Optional[ExpOrStr],
2511        append: bool = True,
2512        dialect: DialectType = None,
2513        copy: bool = True,
2514        **opts,
2515    ) -> Select:
2516        """
2517        Set the GROUP BY expression.
2518
2519        Example:
2520            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2521            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2522
2523        Args:
2524            *expressions: the SQL code strings to parse.
2525                If a `Group` instance is passed, this is used as-is.
2526                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2527                If nothing is passed in then a group by is not applied to the expression
2528            append: if `True`, add to any existing expressions.
2529                Otherwise, this flattens all the `Group` expression into a single expression.
2530            dialect: the dialect used to parse the input expression.
2531            copy: if `False`, modify this expression instance in-place.
2532            opts: other options to use to parse the input expressions.
2533
2534        Returns:
2535            The modified Select expression.
2536        """
2537        if not expressions:
2538            return self if not copy else self.copy()
2539
2540        return _apply_child_list_builder(
2541            *expressions,
2542            instance=self,
2543            arg="group",
2544            append=append,
2545            copy=copy,
2546            prefix="GROUP BY",
2547            into=Group,
2548            dialect=dialect,
2549            **opts,
2550        )
2551
2552    def order_by(
2553        self,
2554        *expressions: t.Optional[ExpOrStr],
2555        append: bool = True,
2556        dialect: DialectType = None,
2557        copy: bool = True,
2558        **opts,
2559    ) -> Select:
2560        """
2561        Set the ORDER BY expression.
2562
2563        Example:
2564            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2565            'SELECT x FROM tbl ORDER BY x DESC'
2566
2567        Args:
2568            *expressions: the SQL code strings to parse.
2569                If a `Group` instance is passed, this is used as-is.
2570                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2571            append: if `True`, add to any existing expressions.
2572                Otherwise, this flattens all the `Order` expression into a single expression.
2573            dialect: the dialect used to parse the input expression.
2574            copy: if `False`, modify this expression instance in-place.
2575            opts: other options to use to parse the input expressions.
2576
2577        Returns:
2578            The modified Select expression.
2579        """
2580        return _apply_child_list_builder(
2581            *expressions,
2582            instance=self,
2583            arg="order",
2584            append=append,
2585            copy=copy,
2586            prefix="ORDER BY",
2587            into=Order,
2588            dialect=dialect,
2589            **opts,
2590        )
2591
2592    def sort_by(
2593        self,
2594        *expressions: t.Optional[ExpOrStr],
2595        append: bool = True,
2596        dialect: DialectType = None,
2597        copy: bool = True,
2598        **opts,
2599    ) -> Select:
2600        """
2601        Set the SORT BY expression.
2602
2603        Example:
2604            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2605            'SELECT x FROM tbl SORT BY x DESC'
2606
2607        Args:
2608            *expressions: the SQL code strings to parse.
2609                If a `Group` instance is passed, this is used as-is.
2610                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2611            append: if `True`, add to any existing expressions.
2612                Otherwise, this flattens all the `Order` expression into a single expression.
2613            dialect: the dialect used to parse the input expression.
2614            copy: if `False`, modify this expression instance in-place.
2615            opts: other options to use to parse the input expressions.
2616
2617        Returns:
2618            The modified Select expression.
2619        """
2620        return _apply_child_list_builder(
2621            *expressions,
2622            instance=self,
2623            arg="sort",
2624            append=append,
2625            copy=copy,
2626            prefix="SORT BY",
2627            into=Sort,
2628            dialect=dialect,
2629            **opts,
2630        )
2631
2632    def cluster_by(
2633        self,
2634        *expressions: t.Optional[ExpOrStr],
2635        append: bool = True,
2636        dialect: DialectType = None,
2637        copy: bool = True,
2638        **opts,
2639    ) -> Select:
2640        """
2641        Set the CLUSTER BY expression.
2642
2643        Example:
2644            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2645            'SELECT x FROM tbl CLUSTER BY x DESC'
2646
2647        Args:
2648            *expressions: the SQL code strings to parse.
2649                If a `Group` instance is passed, this is used as-is.
2650                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2651            append: if `True`, add to any existing expressions.
2652                Otherwise, this flattens all the `Order` expression into a single expression.
2653            dialect: the dialect used to parse the input expression.
2654            copy: if `False`, modify this expression instance in-place.
2655            opts: other options to use to parse the input expressions.
2656
2657        Returns:
2658            The modified Select expression.
2659        """
2660        return _apply_child_list_builder(
2661            *expressions,
2662            instance=self,
2663            arg="cluster",
2664            append=append,
2665            copy=copy,
2666            prefix="CLUSTER BY",
2667            into=Cluster,
2668            dialect=dialect,
2669            **opts,
2670        )
2671
2672    def limit(
2673        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2674    ) -> Select:
2675        """
2676        Set the LIMIT expression.
2677
2678        Example:
2679            >>> Select().from_("tbl").select("x").limit(10).sql()
2680            'SELECT x FROM tbl LIMIT 10'
2681
2682        Args:
2683            expression: the SQL code string to parse.
2684                This can also be an integer.
2685                If a `Limit` instance is passed, this is used as-is.
2686                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2687            dialect: the dialect used to parse the input expression.
2688            copy: if `False`, modify this expression instance in-place.
2689            opts: other options to use to parse the input expressions.
2690
2691        Returns:
2692            Select: the modified expression.
2693        """
2694        return _apply_builder(
2695            expression=expression,
2696            instance=self,
2697            arg="limit",
2698            into=Limit,
2699            prefix="LIMIT",
2700            dialect=dialect,
2701            copy=copy,
2702            **opts,
2703        )
2704
2705    def offset(
2706        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2707    ) -> Select:
2708        """
2709        Set the OFFSET expression.
2710
2711        Example:
2712            >>> Select().from_("tbl").select("x").offset(10).sql()
2713            'SELECT x FROM tbl OFFSET 10'
2714
2715        Args:
2716            expression: the SQL code string to parse.
2717                This can also be an integer.
2718                If a `Offset` instance is passed, this is used as-is.
2719                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2720            dialect: the dialect used to parse the input expression.
2721            copy: if `False`, modify this expression instance in-place.
2722            opts: other options to use to parse the input expressions.
2723
2724        Returns:
2725            The modified Select expression.
2726        """
2727        return _apply_builder(
2728            expression=expression,
2729            instance=self,
2730            arg="offset",
2731            into=Offset,
2732            prefix="OFFSET",
2733            dialect=dialect,
2734            copy=copy,
2735            **opts,
2736        )
2737
2738    def select(
2739        self,
2740        *expressions: t.Optional[ExpOrStr],
2741        append: bool = True,
2742        dialect: DialectType = None,
2743        copy: bool = True,
2744        **opts,
2745    ) -> Select:
2746        """
2747        Append to or set the SELECT expressions.
2748
2749        Example:
2750            >>> Select().select("x", "y").sql()
2751            'SELECT x, y'
2752
2753        Args:
2754            *expressions: the SQL code strings to parse.
2755                If an `Expression` instance is passed, it will be used as-is.
2756            append: if `True`, add to any existing expressions.
2757                Otherwise, this resets the expressions.
2758            dialect: the dialect used to parse the input expressions.
2759            copy: if `False`, modify this expression instance in-place.
2760            opts: other options to use to parse the input expressions.
2761
2762        Returns:
2763            The modified Select expression.
2764        """
2765        return _apply_list_builder(
2766            *expressions,
2767            instance=self,
2768            arg="expressions",
2769            append=append,
2770            dialect=dialect,
2771            copy=copy,
2772            **opts,
2773        )
2774
2775    def lateral(
2776        self,
2777        *expressions: t.Optional[ExpOrStr],
2778        append: bool = True,
2779        dialect: DialectType = None,
2780        copy: bool = True,
2781        **opts,
2782    ) -> Select:
2783        """
2784        Append to or set the LATERAL expressions.
2785
2786        Example:
2787            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2788            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2789
2790        Args:
2791            *expressions: the SQL code strings to parse.
2792                If an `Expression` instance is passed, it will be used as-is.
2793            append: if `True`, add to any existing expressions.
2794                Otherwise, this resets the expressions.
2795            dialect: the dialect used to parse the input expressions.
2796            copy: if `False`, modify this expression instance in-place.
2797            opts: other options to use to parse the input expressions.
2798
2799        Returns:
2800            The modified Select expression.
2801        """
2802        return _apply_list_builder(
2803            *expressions,
2804            instance=self,
2805            arg="laterals",
2806            append=append,
2807            into=Lateral,
2808            prefix="LATERAL VIEW",
2809            dialect=dialect,
2810            copy=copy,
2811            **opts,
2812        )
2813
2814    def join(
2815        self,
2816        expression: ExpOrStr,
2817        on: t.Optional[ExpOrStr] = None,
2818        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2819        append: bool = True,
2820        join_type: t.Optional[str] = None,
2821        join_alias: t.Optional[Identifier | str] = None,
2822        dialect: DialectType = None,
2823        copy: bool = True,
2824        **opts,
2825    ) -> Select:
2826        """
2827        Append to or set the JOIN expressions.
2828
2829        Example:
2830            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2831            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2832
2833            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2834            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2835
2836            Use `join_type` to change the type of join:
2837
2838            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2839            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2840
2841        Args:
2842            expression: the SQL code string to parse.
2843                If an `Expression` instance is passed, it will be used as-is.
2844            on: optionally specify the join "on" criteria as a SQL string.
2845                If an `Expression` instance is passed, it will be used as-is.
2846            using: optionally specify the join "using" criteria as a SQL string.
2847                If an `Expression` instance is passed, it will be used as-is.
2848            append: if `True`, add to any existing expressions.
2849                Otherwise, this resets the expressions.
2850            join_type: if set, alter the parsed join type.
2851            join_alias: an optional alias for the joined source.
2852            dialect: the dialect used to parse the input expressions.
2853            copy: if `False`, modify this expression instance in-place.
2854            opts: other options to use to parse the input expressions.
2855
2856        Returns:
2857            Select: the modified expression.
2858        """
2859        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2860
2861        try:
2862            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2863        except ParseError:
2864            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2865
2866        join = expression if isinstance(expression, Join) else Join(this=expression)
2867
2868        if isinstance(join.this, Select):
2869            join.this.replace(join.this.subquery())
2870
2871        if join_type:
2872            method: t.Optional[Token]
2873            side: t.Optional[Token]
2874            kind: t.Optional[Token]
2875
2876            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2877
2878            if method:
2879                join.set("method", method.text)
2880            if side:
2881                join.set("side", side.text)
2882            if kind:
2883                join.set("kind", kind.text)
2884
2885        if on:
2886            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2887            join.set("on", on)
2888
2889        if using:
2890            join = _apply_list_builder(
2891                *ensure_list(using),
2892                instance=join,
2893                arg="using",
2894                append=append,
2895                copy=copy,
2896                **opts,
2897            )
2898
2899        if join_alias:
2900            join.set("this", alias_(join.this, join_alias, table=True))
2901
2902        return _apply_list_builder(
2903            join,
2904            instance=self,
2905            arg="joins",
2906            append=append,
2907            copy=copy,
2908            **opts,
2909        )
2910
2911    def where(
2912        self,
2913        *expressions: t.Optional[ExpOrStr],
2914        append: bool = True,
2915        dialect: DialectType = None,
2916        copy: bool = True,
2917        **opts,
2918    ) -> Select:
2919        """
2920        Append to or set the WHERE expressions.
2921
2922        Example:
2923            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2924            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2925
2926        Args:
2927            *expressions: the SQL code strings to parse.
2928                If an `Expression` instance is passed, it will be used as-is.
2929                Multiple expressions are combined with an AND operator.
2930            append: if `True`, AND the new expressions to any existing expression.
2931                Otherwise, this resets the expression.
2932            dialect: the dialect used to parse the input expressions.
2933            copy: if `False`, modify this expression instance in-place.
2934            opts: other options to use to parse the input expressions.
2935
2936        Returns:
2937            Select: the modified expression.
2938        """
2939        return _apply_conjunction_builder(
2940            *expressions,
2941            instance=self,
2942            arg="where",
2943            append=append,
2944            into=Where,
2945            dialect=dialect,
2946            copy=copy,
2947            **opts,
2948        )
2949
2950    def having(
2951        self,
2952        *expressions: t.Optional[ExpOrStr],
2953        append: bool = True,
2954        dialect: DialectType = None,
2955        copy: bool = True,
2956        **opts,
2957    ) -> Select:
2958        """
2959        Append to or set the HAVING expressions.
2960
2961        Example:
2962            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2963            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2964
2965        Args:
2966            *expressions: the SQL code strings to parse.
2967                If an `Expression` instance is passed, it will be used as-is.
2968                Multiple expressions are combined with an AND operator.
2969            append: if `True`, AND the new expressions to any existing expression.
2970                Otherwise, this resets the expression.
2971            dialect: the dialect used to parse the input expressions.
2972            copy: if `False`, modify this expression instance in-place.
2973            opts: other options to use to parse the input expressions.
2974
2975        Returns:
2976            The modified Select expression.
2977        """
2978        return _apply_conjunction_builder(
2979            *expressions,
2980            instance=self,
2981            arg="having",
2982            append=append,
2983            into=Having,
2984            dialect=dialect,
2985            copy=copy,
2986            **opts,
2987        )
2988
2989    def window(
2990        self,
2991        *expressions: t.Optional[ExpOrStr],
2992        append: bool = True,
2993        dialect: DialectType = None,
2994        copy: bool = True,
2995        **opts,
2996    ) -> Select:
2997        return _apply_list_builder(
2998            *expressions,
2999            instance=self,
3000            arg="windows",
3001            append=append,
3002            into=Window,
3003            dialect=dialect,
3004            copy=copy,
3005            **opts,
3006        )
3007
3008    def qualify(
3009        self,
3010        *expressions: t.Optional[ExpOrStr],
3011        append: bool = True,
3012        dialect: DialectType = None,
3013        copy: bool = True,
3014        **opts,
3015    ) -> Select:
3016        return _apply_conjunction_builder(
3017            *expressions,
3018            instance=self,
3019            arg="qualify",
3020            append=append,
3021            into=Qualify,
3022            dialect=dialect,
3023            copy=copy,
3024            **opts,
3025        )
3026
3027    def distinct(
3028        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3029    ) -> Select:
3030        """
3031        Set the OFFSET expression.
3032
3033        Example:
3034            >>> Select().from_("tbl").select("x").distinct().sql()
3035            'SELECT DISTINCT x FROM tbl'
3036
3037        Args:
3038            ons: the expressions to distinct on
3039            distinct: whether the Select should be distinct
3040            copy: if `False`, modify this expression instance in-place.
3041
3042        Returns:
3043            Select: the modified expression.
3044        """
3045        instance = _maybe_copy(self, copy)
3046        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3047        instance.set("distinct", Distinct(on=on) if distinct else None)
3048        return instance
3049
3050    def ctas(
3051        self,
3052        table: ExpOrStr,
3053        properties: t.Optional[t.Dict] = None,
3054        dialect: DialectType = None,
3055        copy: bool = True,
3056        **opts,
3057    ) -> Create:
3058        """
3059        Convert this expression to a CREATE TABLE AS statement.
3060
3061        Example:
3062            >>> Select().select("*").from_("tbl").ctas("x").sql()
3063            'CREATE TABLE x AS SELECT * FROM tbl'
3064
3065        Args:
3066            table: the SQL code string to parse as the table name.
3067                If another `Expression` instance is passed, it will be used as-is.
3068            properties: an optional mapping of table properties
3069            dialect: the dialect used to parse the input table.
3070            copy: if `False`, modify this expression instance in-place.
3071            opts: other options to use to parse the input table.
3072
3073        Returns:
3074            The new Create expression.
3075        """
3076        instance = _maybe_copy(self, copy)
3077        table_expression = maybe_parse(
3078            table,
3079            into=Table,
3080            dialect=dialect,
3081            **opts,
3082        )
3083        properties_expression = None
3084        if properties:
3085            properties_expression = Properties.from_dict(properties)
3086
3087        return Create(
3088            this=table_expression,
3089            kind="table",
3090            expression=instance,
3091            properties=properties_expression,
3092        )
3093
3094    def lock(self, update: bool = True, copy: bool = True) -> Select:
3095        """
3096        Set the locking read mode for this expression.
3097
3098        Examples:
3099            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3100            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3101
3102            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3103            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3104
3105        Args:
3106            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3107            copy: if `False`, modify this expression instance in-place.
3108
3109        Returns:
3110            The modified expression.
3111        """
3112        inst = _maybe_copy(self, copy)
3113        inst.set("locks", [Lock(update=update)])
3114
3115        return inst
3116
3117    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3118        """
3119        Set hints for this expression.
3120
3121        Examples:
3122            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3123            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3124
3125        Args:
3126            hints: The SQL code strings to parse as the hints.
3127                If an `Expression` instance is passed, it will be used as-is.
3128            dialect: The dialect used to parse the hints.
3129            copy: If `False`, modify this expression instance in-place.
3130
3131        Returns:
3132            The modified expression.
3133        """
3134        inst = _maybe_copy(self, copy)
3135        inst.set(
3136            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3137        )
3138
3139        return inst
3140
3141    @property
3142    def named_selects(self) -> t.List[str]:
3143        return [e.output_name for e in self.expressions if e.alias_or_name]
3144
3145    @property
3146    def is_star(self) -> bool:
3147        return any(expression.is_star for expression in self.expressions)
3148
3149    @property
3150    def selects(self) -> t.List[Expression]:
3151        return self.expressions
3152
3153
3154class Subquery(DerivedTable, Unionable):
3155    arg_types = {
3156        "this": True,
3157        "alias": False,
3158        "with": False,
3159        **QUERY_MODIFIERS,
3160    }
3161
3162    def unnest(self):
3163        """
3164        Returns the first non subquery.
3165        """
3166        expression = self
3167        while isinstance(expression, Subquery):
3168            expression = expression.this
3169        return expression
3170
3171    @property
3172    def is_star(self) -> bool:
3173        return self.this.is_star
3174
3175    @property
3176    def output_name(self) -> str:
3177        return self.alias
3178
3179
3180class TableSample(Expression):
3181    arg_types = {
3182        "this": False,
3183        "method": False,
3184        "bucket_numerator": False,
3185        "bucket_denominator": False,
3186        "bucket_field": False,
3187        "percent": False,
3188        "rows": False,
3189        "size": False,
3190        "seed": False,
3191        "kind": False,
3192    }
3193
3194
3195class Tag(Expression):
3196    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3197
3198    arg_types = {
3199        "this": False,
3200        "prefix": False,
3201        "postfix": False,
3202    }
3203
3204
3205# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3206# https://duckdb.org/docs/sql/statements/pivot
3207class Pivot(Expression):
3208    arg_types = {
3209        "this": False,
3210        "alias": False,
3211        "expressions": True,
3212        "field": False,
3213        "unpivot": False,
3214        "using": False,
3215        "group": False,
3216        "columns": False,
3217    }
3218
3219
3220class Window(Expression):
3221    arg_types = {
3222        "this": True,
3223        "partition_by": False,
3224        "order": False,
3225        "spec": False,
3226        "alias": False,
3227        "over": False,
3228        "first": False,
3229    }
3230
3231
3232class WindowSpec(Expression):
3233    arg_types = {
3234        "kind": False,
3235        "start": False,
3236        "start_side": False,
3237        "end": False,
3238        "end_side": False,
3239    }
3240
3241
3242class Where(Expression):
3243    pass
3244
3245
3246class Star(Expression):
3247    arg_types = {"except": False, "replace": False}
3248
3249    @property
3250    def name(self) -> str:
3251        return "*"
3252
3253    @property
3254    def output_name(self) -> str:
3255        return self.name
3256
3257
3258class Parameter(Condition):
3259    arg_types = {"this": True, "wrapped": False}
3260
3261
3262class SessionParameter(Condition):
3263    arg_types = {"this": True, "kind": False}
3264
3265
3266class Placeholder(Condition):
3267    arg_types = {"this": False, "kind": False}
3268
3269
3270class Null(Condition):
3271    arg_types: t.Dict[str, t.Any] = {}
3272
3273    @property
3274    def name(self) -> str:
3275        return "NULL"
3276
3277
3278class Boolean(Condition):
3279    pass
3280
3281
3282class DataTypeSize(Expression):
3283    arg_types = {"this": True, "expression": False}
3284
3285
3286class DataType(Expression):
3287    arg_types = {
3288        "this": True,
3289        "expressions": False,
3290        "nested": False,
3291        "values": False,
3292        "prefix": False,
3293    }
3294
3295    class Type(AutoName):
3296        ARRAY = auto()
3297        BIGDECIMAL = auto()
3298        BIGINT = auto()
3299        BIGSERIAL = auto()
3300        BINARY = auto()
3301        BIT = auto()
3302        BOOLEAN = auto()
3303        CHAR = auto()
3304        DATE = auto()
3305        DATETIME = auto()
3306        DATETIME64 = auto()
3307        ENUM = auto()
3308        INT4RANGE = auto()
3309        INT4MULTIRANGE = auto()
3310        INT8RANGE = auto()
3311        INT8MULTIRANGE = auto()
3312        NUMRANGE = auto()
3313        NUMMULTIRANGE = auto()
3314        TSRANGE = auto()
3315        TSMULTIRANGE = auto()
3316        TSTZRANGE = auto()
3317        TSTZMULTIRANGE = auto()
3318        DATERANGE = auto()
3319        DATEMULTIRANGE = auto()
3320        DECIMAL = auto()
3321        DOUBLE = auto()
3322        FLOAT = auto()
3323        GEOGRAPHY = auto()
3324        GEOMETRY = auto()
3325        HLLSKETCH = auto()
3326        HSTORE = auto()
3327        IMAGE = auto()
3328        INET = auto()
3329        INT = auto()
3330        INT128 = auto()
3331        INT256 = auto()
3332        INTERVAL = auto()
3333        JSON = auto()
3334        JSONB = auto()
3335        LONGBLOB = auto()
3336        LONGTEXT = auto()
3337        MAP = auto()
3338        MEDIUMBLOB = auto()
3339        MEDIUMTEXT = auto()
3340        MONEY = auto()
3341        NCHAR = auto()
3342        NULL = auto()
3343        NULLABLE = auto()
3344        NVARCHAR = auto()
3345        OBJECT = auto()
3346        ROWVERSION = auto()
3347        SERIAL = auto()
3348        SET = auto()
3349        SMALLINT = auto()
3350        SMALLMONEY = auto()
3351        SMALLSERIAL = auto()
3352        STRUCT = auto()
3353        SUPER = auto()
3354        TEXT = auto()
3355        TIME = auto()
3356        TIMESTAMP = auto()
3357        TIMESTAMPTZ = auto()
3358        TIMESTAMPLTZ = auto()
3359        TINYINT = auto()
3360        UBIGINT = auto()
3361        UINT = auto()
3362        USMALLINT = auto()
3363        UTINYINT = auto()
3364        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3365        UINT128 = auto()
3366        UINT256 = auto()
3367        UNIQUEIDENTIFIER = auto()
3368        USERDEFINED = "USER-DEFINED"
3369        UUID = auto()
3370        VARBINARY = auto()
3371        VARCHAR = auto()
3372        VARIANT = auto()
3373        XML = auto()
3374
3375    TEXT_TYPES = {
3376        Type.CHAR,
3377        Type.NCHAR,
3378        Type.VARCHAR,
3379        Type.NVARCHAR,
3380        Type.TEXT,
3381    }
3382
3383    INTEGER_TYPES = {
3384        Type.INT,
3385        Type.TINYINT,
3386        Type.SMALLINT,
3387        Type.BIGINT,
3388        Type.INT128,
3389        Type.INT256,
3390    }
3391
3392    FLOAT_TYPES = {
3393        Type.FLOAT,
3394        Type.DOUBLE,
3395    }
3396
3397    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3398
3399    TEMPORAL_TYPES = {
3400        Type.TIME,
3401        Type.TIMESTAMP,
3402        Type.TIMESTAMPTZ,
3403        Type.TIMESTAMPLTZ,
3404        Type.DATE,
3405        Type.DATETIME,
3406        Type.DATETIME64,
3407    }
3408
3409    META_TYPES = {"UNKNOWN", "NULL"}
3410
3411    @classmethod
3412    def build(
3413        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3414    ) -> DataType:
3415        from sqlglot import parse_one
3416
3417        if isinstance(dtype, str):
3418            upper = dtype.upper()
3419            if upper in DataType.META_TYPES:
3420                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3421            else:
3422                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3423
3424            if data_type_exp is None:
3425                raise ValueError(f"Unparsable data type value: {dtype}")
3426        elif isinstance(dtype, DataType.Type):
3427            data_type_exp = DataType(this=dtype)
3428        elif isinstance(dtype, DataType):
3429            return dtype
3430        else:
3431            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3432
3433        return DataType(**{**data_type_exp.args, **kwargs})
3434
3435    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3436        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3437
3438
3439# https://www.postgresql.org/docs/15/datatype-pseudo.html
3440class PseudoType(Expression):
3441    pass
3442
3443
3444# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3445class SubqueryPredicate(Predicate):
3446    pass
3447
3448
3449class All(SubqueryPredicate):
3450    pass
3451
3452
3453class Any(SubqueryPredicate):
3454    pass
3455
3456
3457class Exists(SubqueryPredicate):
3458    pass
3459
3460
3461# Commands to interact with the databases or engines. For most of the command
3462# expressions we parse whatever comes after the command's name as a string.
3463class Command(Expression):
3464    arg_types = {"this": True, "expression": False}
3465
3466
3467class Transaction(Expression):
3468    arg_types = {"this": False, "modes": False}
3469
3470
3471class Commit(Expression):
3472    arg_types = {"chain": False}
3473
3474
3475class Rollback(Expression):
3476    arg_types = {"savepoint": False}
3477
3478
3479class AlterTable(Expression):
3480    arg_types = {"this": True, "actions": True, "exists": False}
3481
3482
3483class AddConstraint(Expression):
3484    arg_types = {"this": False, "expression": False, "enforced": False}
3485
3486
3487class DropPartition(Expression):
3488    arg_types = {"expressions": True, "exists": False}
3489
3490
3491# Binary expressions like (ADD a b)
3492class Binary(Condition):
3493    arg_types = {"this": True, "expression": True}
3494
3495    @property
3496    def left(self):
3497        return self.this
3498
3499    @property
3500    def right(self):
3501        return self.expression
3502
3503
3504class Add(Binary):
3505    pass
3506
3507
3508class Connector(Binary):
3509    pass
3510
3511
3512class And(Connector):
3513    pass
3514
3515
3516class Or(Connector):
3517    pass
3518
3519
3520class BitwiseAnd(Binary):
3521    pass
3522
3523
3524class BitwiseLeftShift(Binary):
3525    pass
3526
3527
3528class BitwiseOr(Binary):
3529    pass
3530
3531
3532class BitwiseRightShift(Binary):
3533    pass
3534
3535
3536class BitwiseXor(Binary):
3537    pass
3538
3539
3540class Div(Binary):
3541    pass
3542
3543
3544class Overlaps(Binary):
3545    pass
3546
3547
3548class Dot(Binary):
3549    @property
3550    def name(self) -> str:
3551        return self.expression.name
3552
3553    @property
3554    def output_name(self) -> str:
3555        return self.name
3556
3557    @classmethod
3558    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3559        """Build a Dot object with a sequence of expressions."""
3560        if len(expressions) < 2:
3561            raise ValueError(f"Dot requires >= 2 expressions.")
3562
3563        a, b, *expressions = expressions
3564        dot = Dot(this=a, expression=b)
3565
3566        for expression in expressions:
3567            dot = Dot(this=dot, expression=expression)
3568
3569        return dot
3570
3571
3572class DPipe(Binary):
3573    pass
3574
3575
3576class SafeDPipe(DPipe):
3577    pass
3578
3579
3580class EQ(Binary, Predicate):
3581    pass
3582
3583
3584class NullSafeEQ(Binary, Predicate):
3585    pass
3586
3587
3588class NullSafeNEQ(Binary, Predicate):
3589    pass
3590
3591
3592class Distance(Binary):
3593    pass
3594
3595
3596class Escape(Binary):
3597    pass
3598
3599
3600class Glob(Binary, Predicate):
3601    pass
3602
3603
3604class GT(Binary, Predicate):
3605    pass
3606
3607
3608class GTE(Binary, Predicate):
3609    pass
3610
3611
3612class ILike(Binary, Predicate):
3613    pass
3614
3615
3616class ILikeAny(Binary, Predicate):
3617    pass
3618
3619
3620class IntDiv(Binary):
3621    pass
3622
3623
3624class Is(Binary, Predicate):
3625    pass
3626
3627
3628class Kwarg(Binary):
3629    """Kwarg in special functions like func(kwarg => y)."""
3630
3631
3632class Like(Binary, Predicate):
3633    pass
3634
3635
3636class LikeAny(Binary, Predicate):
3637    pass
3638
3639
3640class LT(Binary, Predicate):
3641    pass
3642
3643
3644class LTE(Binary, Predicate):
3645    pass
3646
3647
3648class Mod(Binary):
3649    pass
3650
3651
3652class Mul(Binary):
3653    pass
3654
3655
3656class NEQ(Binary, Predicate):
3657    pass
3658
3659
3660class SimilarTo(Binary, Predicate):
3661    pass
3662
3663
3664class Slice(Binary):
3665    arg_types = {"this": False, "expression": False}
3666
3667
3668class Sub(Binary):
3669    pass
3670
3671
3672class ArrayOverlaps(Binary):
3673    pass
3674
3675
3676# Unary Expressions
3677# (NOT a)
3678class Unary(Condition):
3679    pass
3680
3681
3682class BitwiseNot(Unary):
3683    pass
3684
3685
3686class Not(Unary):
3687    pass
3688
3689
3690class Paren(Unary):
3691    arg_types = {"this": True, "with": False}
3692
3693    @property
3694    def output_name(self) -> str:
3695        return self.this.name
3696
3697
3698class Neg(Unary):
3699    pass
3700
3701
3702class Alias(Expression):
3703    arg_types = {"this": True, "alias": False}
3704
3705    @property
3706    def output_name(self) -> str:
3707        return self.alias
3708
3709
3710class Aliases(Expression):
3711    arg_types = {"this": True, "expressions": True}
3712
3713    @property
3714    def aliases(self):
3715        return self.expressions
3716
3717
3718class AtTimeZone(Expression):
3719    arg_types = {"this": True, "zone": True}
3720
3721
3722class Between(Predicate):
3723    arg_types = {"this": True, "low": True, "high": True}
3724
3725
3726class Bracket(Condition):
3727    arg_types = {"this": True, "expressions": True}
3728
3729
3730class SafeBracket(Bracket):
3731    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3732
3733
3734class Distinct(Expression):
3735    arg_types = {"expressions": False, "on": False}
3736
3737
3738class In(Predicate):
3739    arg_types = {
3740        "this": True,
3741        "expressions": False,
3742        "query": False,
3743        "unnest": False,
3744        "field": False,
3745        "is_global": False,
3746    }
3747
3748
3749class TimeUnit(Expression):
3750    """Automatically converts unit arg into a var."""
3751
3752    arg_types = {"unit": False}
3753
3754    def __init__(self, **args):
3755        unit = args.get("unit")
3756        if isinstance(unit, (Column, Literal)):
3757            args["unit"] = Var(this=unit.name)
3758        elif isinstance(unit, Week):
3759            unit.set("this", Var(this=unit.this.name))
3760
3761        super().__init__(**args)
3762
3763
3764class Interval(TimeUnit):
3765    arg_types = {"this": False, "unit": False}
3766
3767    @property
3768    def unit(self) -> t.Optional[Var]:
3769        return self.args.get("unit")
3770
3771
3772class IgnoreNulls(Expression):
3773    pass
3774
3775
3776class RespectNulls(Expression):
3777    pass
3778
3779
3780# Functions
3781class Func(Condition):
3782    """
3783    The base class for all function expressions.
3784
3785    Attributes:
3786        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3787            treated as a variable length argument and the argument's value will be stored as a list.
3788        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3789            for this function expression. These values are used to map this node to a name during parsing
3790            as well as to provide the function's name during SQL string generation. By default the SQL
3791            name is set to the expression's class name transformed to snake case.
3792    """
3793
3794    is_var_len_args = False
3795
3796    @classmethod
3797    def from_arg_list(cls, args):
3798        if cls.is_var_len_args:
3799            all_arg_keys = list(cls.arg_types)
3800            # If this function supports variable length argument treat the last argument as such.
3801            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3802            num_non_var = len(non_var_len_arg_keys)
3803
3804            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3805            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3806        else:
3807            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3808
3809        return cls(**args_dict)
3810
3811    @classmethod
3812    def sql_names(cls):
3813        if cls is Func:
3814            raise NotImplementedError(
3815                "SQL name is only supported by concrete function implementations"
3816            )
3817        if "_sql_names" not in cls.__dict__:
3818            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3819        return cls._sql_names
3820
3821    @classmethod
3822    def sql_name(cls):
3823        return cls.sql_names()[0]
3824
3825    @classmethod
3826    def default_parser_mappings(cls):
3827        return {name: cls.from_arg_list for name in cls.sql_names()}
3828
3829
3830class AggFunc(Func):
3831    pass
3832
3833
3834class ParameterizedAgg(AggFunc):
3835    arg_types = {"this": True, "expressions": True, "params": True}
3836
3837
3838class Abs(Func):
3839    pass
3840
3841
3842class Anonymous(Func):
3843    arg_types = {"this": True, "expressions": False}
3844    is_var_len_args = True
3845
3846
3847# https://docs.snowflake.com/en/sql-reference/functions/hll
3848# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3849class Hll(AggFunc):
3850    arg_types = {"this": True, "expressions": False}
3851    is_var_len_args = True
3852
3853
3854class ApproxDistinct(AggFunc):
3855    arg_types = {"this": True, "accuracy": False}
3856    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3857
3858
3859class Array(Func):
3860    arg_types = {"expressions": False}
3861    is_var_len_args = True
3862
3863
3864# https://docs.snowflake.com/en/sql-reference/functions/to_char
3865class ToChar(Func):
3866    arg_types = {"this": True, "format": False}
3867
3868
3869class GenerateSeries(Func):
3870    arg_types = {"start": True, "end": True, "step": False}
3871
3872
3873class ArrayAgg(AggFunc):
3874    pass
3875
3876
3877class ArrayAll(Func):
3878    arg_types = {"this": True, "expression": True}
3879
3880
3881class ArrayAny(Func):
3882    arg_types = {"this": True, "expression": True}
3883
3884
3885class ArrayConcat(Func):
3886    arg_types = {"this": True, "expressions": False}
3887    is_var_len_args = True
3888
3889
3890class ArrayContains(Binary, Func):
3891    pass
3892
3893
3894class ArrayContained(Binary):
3895    pass
3896
3897
3898class ArrayFilter(Func):
3899    arg_types = {"this": True, "expression": True}
3900    _sql_names = ["FILTER", "ARRAY_FILTER"]
3901
3902
3903class ArrayJoin(Func):
3904    arg_types = {"this": True, "expression": True, "null": False}
3905
3906
3907class ArraySize(Func):
3908    arg_types = {"this": True, "expression": False}
3909
3910
3911class ArraySort(Func):
3912    arg_types = {"this": True, "expression": False}
3913
3914
3915class ArraySum(Func):
3916    pass
3917
3918
3919class ArrayUnionAgg(AggFunc):
3920    pass
3921
3922
3923class Avg(AggFunc):
3924    pass
3925
3926
3927class AnyValue(AggFunc):
3928    arg_types = {"this": True, "having": False, "max": False}
3929
3930
3931class Case(Func):
3932    arg_types = {"this": False, "ifs": True, "default": False}
3933
3934    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3935        instance = _maybe_copy(self, copy)
3936        instance.append(
3937            "ifs",
3938            If(
3939                this=maybe_parse(condition, copy=copy, **opts),
3940                true=maybe_parse(then, copy=copy, **opts),
3941            ),
3942        )
3943        return instance
3944
3945    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3946        instance = _maybe_copy(self, copy)
3947        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3948        return instance
3949
3950
3951class Cast(Func):
3952    arg_types = {"this": True, "to": True, "format": False}
3953
3954    @property
3955    def name(self) -> str:
3956        return self.this.name
3957
3958    @property
3959    def to(self) -> DataType:
3960        return self.args["to"]
3961
3962    @property
3963    def output_name(self) -> str:
3964        return self.name
3965
3966    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3967        return self.to.is_type(*dtypes)
3968
3969
3970class CastToStrType(Func):
3971    arg_types = {"this": True, "expression": True}
3972
3973
3974class Collate(Binary):
3975    pass
3976
3977
3978class TryCast(Cast):
3979    pass
3980
3981
3982class Ceil(Func):
3983    arg_types = {"this": True, "decimals": False}
3984    _sql_names = ["CEIL", "CEILING"]
3985
3986
3987class Coalesce(Func):
3988    arg_types = {"this": True, "expressions": False}
3989    is_var_len_args = True
3990    _sql_names = ["COALESCE", "IFNULL", "NVL"]
3991
3992
3993class Concat(Func):
3994    arg_types = {"expressions": True}
3995    is_var_len_args = True
3996
3997
3998class SafeConcat(Concat):
3999    pass
4000
4001
4002class ConcatWs(Concat):
4003    _sql_names = ["CONCAT_WS"]
4004
4005
4006class Count(AggFunc):
4007    arg_types = {"this": False, "expressions": False}
4008    is_var_len_args = True
4009
4010
4011class CountIf(AggFunc):
4012    pass
4013
4014
4015class CurrentDate(Func):
4016    arg_types = {"this": False}
4017
4018
4019class CurrentDatetime(Func):
4020    arg_types = {"this": False}
4021
4022
4023class CurrentTime(Func):
4024    arg_types = {"this": False}
4025
4026
4027class CurrentTimestamp(Func):
4028    arg_types = {"this": False}
4029
4030
4031class CurrentUser(Func):
4032    arg_types = {"this": False}
4033
4034
4035class DateAdd(Func, TimeUnit):
4036    arg_types = {"this": True, "expression": True, "unit": False}
4037
4038
4039class DateSub(Func, TimeUnit):
4040    arg_types = {"this": True, "expression": True, "unit": False}
4041
4042
4043class DateDiff(Func, TimeUnit):
4044    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4045    arg_types = {"this": True, "expression": True, "unit": False}
4046
4047
4048class DateTrunc(Func):
4049    arg_types = {"unit": True, "this": True, "zone": False}
4050
4051
4052class DatetimeAdd(Func, TimeUnit):
4053    arg_types = {"this": True, "expression": True, "unit": False}
4054
4055
4056class DatetimeSub(Func, TimeUnit):
4057    arg_types = {"this": True, "expression": True, "unit": False}
4058
4059
4060class DatetimeDiff(Func, TimeUnit):
4061    arg_types = {"this": True, "expression": True, "unit": False}
4062
4063
4064class DatetimeTrunc(Func, TimeUnit):
4065    arg_types = {"this": True, "unit": True, "zone": False}
4066
4067
4068class DayOfWeek(Func):
4069    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4070
4071
4072class DayOfMonth(Func):
4073    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4074
4075
4076class DayOfYear(Func):
4077    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4078
4079
4080class WeekOfYear(Func):
4081    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4082
4083
4084class LastDateOfMonth(Func):
4085    pass
4086
4087
4088class Extract(Func):
4089    arg_types = {"this": True, "expression": True}
4090
4091
4092class TimestampAdd(Func, TimeUnit):
4093    arg_types = {"this": True, "expression": True, "unit": False}
4094
4095
4096class TimestampSub(Func, TimeUnit):
4097    arg_types = {"this": True, "expression": True, "unit": False}
4098
4099
4100class TimestampDiff(Func, TimeUnit):
4101    arg_types = {"this": True, "expression": True, "unit": False}
4102
4103
4104class TimestampTrunc(Func, TimeUnit):
4105    arg_types = {"this": True, "unit": True, "zone": False}
4106
4107
4108class TimeAdd(Func, TimeUnit):
4109    arg_types = {"this": True, "expression": True, "unit": False}
4110
4111
4112class TimeSub(Func, TimeUnit):
4113    arg_types = {"this": True, "expression": True, "unit": False}
4114
4115
4116class TimeDiff(Func, TimeUnit):
4117    arg_types = {"this": True, "expression": True, "unit": False}
4118
4119
4120class TimeTrunc(Func, TimeUnit):
4121    arg_types = {"this": True, "unit": True, "zone": False}
4122
4123
4124class DateFromParts(Func):
4125    _sql_names = ["DATEFROMPARTS"]
4126    arg_types = {"year": True, "month": True, "day": True}
4127
4128
4129class DateStrToDate(Func):
4130    pass
4131
4132
4133class DateToDateStr(Func):
4134    pass
4135
4136
4137class DateToDi(Func):
4138    pass
4139
4140
4141# https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
4142class Date(Func):
4143    arg_types = {"this": True, "zone": False}
4144
4145
4146class Day(Func):
4147    pass
4148
4149
4150class Decode(Func):
4151    arg_types = {"this": True, "charset": True, "replace": False}
4152
4153
4154class DiToDate(Func):
4155    pass
4156
4157
4158class Encode(Func):
4159    arg_types = {"this": True, "charset": True}
4160
4161
4162class Exp(Func):
4163    pass
4164
4165
4166class Explode(Func):
4167    pass
4168
4169
4170class Floor(Func):
4171    arg_types = {"this": True, "decimals": False}
4172
4173
4174class FromBase64(Func):
4175    pass
4176
4177
4178class ToBase64(Func):
4179    pass
4180
4181
4182class Greatest(Func):
4183    arg_types = {"this": True, "expressions": False}
4184    is_var_len_args = True
4185
4186
4187class GroupConcat(Func):
4188    arg_types = {"this": True, "separator": False}
4189
4190
4191class Hex(Func):
4192    pass
4193
4194
4195class If(Func):
4196    arg_types = {"this": True, "true": True, "false": False}
4197
4198
4199class Initcap(Func):
4200    arg_types = {"this": True, "expression": False}
4201
4202
4203class JSONKeyValue(Expression):
4204    arg_types = {"this": True, "expression": True}
4205
4206
4207class JSONObject(Func):
4208    arg_types = {
4209        "expressions": False,
4210        "null_handling": False,
4211        "unique_keys": False,
4212        "return_type": False,
4213        "format_json": False,
4214        "encoding": False,
4215    }
4216
4217
4218class OpenJSONColumnDef(Expression):
4219    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4220
4221
4222class OpenJSON(Func):
4223    arg_types = {"this": True, "path": False, "expressions": False}
4224
4225
4226class JSONBContains(Binary):
4227    _sql_names = ["JSONB_CONTAINS"]
4228
4229
4230class JSONExtract(Binary, Func):
4231    _sql_names = ["JSON_EXTRACT"]
4232
4233
4234class JSONExtractScalar(JSONExtract):
4235    _sql_names = ["JSON_EXTRACT_SCALAR"]
4236
4237
4238class JSONBExtract(JSONExtract):
4239    _sql_names = ["JSONB_EXTRACT"]
4240
4241
4242class JSONBExtractScalar(JSONExtract):
4243    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4244
4245
4246class JSONFormat(Func):
4247    arg_types = {"this": False, "options": False}
4248    _sql_names = ["JSON_FORMAT"]
4249
4250
4251# https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of
4252class JSONArrayContains(Binary, Predicate, Func):
4253    _sql_names = ["JSON_ARRAY_CONTAINS"]
4254
4255
4256class Least(Func):
4257    arg_types = {"this": True, "expressions": False}
4258    is_var_len_args = True
4259
4260
4261class Left(Func):
4262    arg_types = {"this": True, "expression": True}
4263
4264
4265class Right(Func):
4266    arg_types = {"this": True, "expression": True}
4267
4268
4269class Length(Func):
4270    _sql_names = ["LENGTH", "LEN"]
4271
4272
4273class Levenshtein(Func):
4274    arg_types = {
4275        "this": True,
4276        "expression": False,
4277        "ins_cost": False,
4278        "del_cost": False,
4279        "sub_cost": False,
4280    }
4281
4282
4283class Ln(Func):
4284    pass
4285
4286
4287class Log(Func):
4288    arg_types = {"this": True, "expression": False}
4289
4290
4291class Log2(Func):
4292    pass
4293
4294
4295class Log10(Func):
4296    pass
4297
4298
4299class LogicalOr(AggFunc):
4300    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4301
4302
4303class LogicalAnd(AggFunc):
4304    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4305
4306
4307class Lower(Func):
4308    _sql_names = ["LOWER", "LCASE"]
4309
4310
4311class Map(Func):
4312    arg_types = {"keys": False, "values": False}
4313
4314
4315class MapFromEntries(Func):
4316    pass
4317
4318
4319class StarMap(Func):
4320    pass
4321
4322
4323class VarMap(Func):
4324    arg_types = {"keys": True, "values": True}
4325    is_var_len_args = True
4326
4327    @property
4328    def keys(self) -> t.List[Expression]:
4329        return self.args["keys"].expressions
4330
4331    @property
4332    def values(self) -> t.List[Expression]:
4333        return self.args["values"].expressions
4334
4335
4336# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4337class MatchAgainst(Func):
4338    arg_types = {"this": True, "expressions": True, "modifier": False}
4339
4340
4341class Max(AggFunc):
4342    arg_types = {"this": True, "expressions": False}
4343    is_var_len_args = True
4344
4345
4346class MD5(Func):
4347    _sql_names = ["MD5"]
4348
4349
4350# Represents the variant of the MD5 function that returns a binary value
4351class MD5Digest(Func):
4352    _sql_names = ["MD5_DIGEST"]
4353
4354
4355class Min(AggFunc):
4356    arg_types = {"this": True, "expressions": False}
4357    is_var_len_args = True
4358
4359
4360class Month(Func):
4361    pass
4362
4363
4364class Nvl2(Func):
4365    arg_types = {"this": True, "true": True, "false": False}
4366
4367
4368class Posexplode(Func):
4369    pass
4370
4371
4372class Pow(Binary, Func):
4373    _sql_names = ["POWER", "POW"]
4374
4375
4376class PercentileCont(AggFunc):
4377    arg_types = {"this": True, "expression": False}
4378
4379
4380class PercentileDisc(AggFunc):
4381    arg_types = {"this": True, "expression": False}
4382
4383
4384class Quantile(AggFunc):
4385    arg_types = {"this": True, "quantile": True}
4386
4387
4388class ApproxQuantile(Quantile):
4389    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4390
4391
4392class RangeN(Func):
4393    arg_types = {"this": True, "expressions": True, "each": False}
4394
4395
4396class ReadCSV(Func):
4397    _sql_names = ["READ_CSV"]
4398    is_var_len_args = True
4399    arg_types = {"this": True, "expressions": False}
4400
4401
4402class Reduce(Func):
4403    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4404
4405
4406class RegexpExtract(Func):
4407    arg_types = {
4408        "this": True,
4409        "expression": True,
4410        "position": False,
4411        "occurrence": False,
4412        "group": False,
4413    }
4414
4415
4416class RegexpLike(Func):
4417    arg_types = {"this": True, "expression": True, "flag": False}
4418
4419
4420class RegexpILike(Func):
4421    arg_types = {"this": True, "expression": True, "flag": False}
4422
4423
4424# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4425# limit is the number of times a pattern is applied
4426class RegexpSplit(Func):
4427    arg_types = {"this": True, "expression": True, "limit": False}
4428
4429
4430class Repeat(Func):
4431    arg_types = {"this": True, "times": True}
4432
4433
4434class Round(Func):
4435    arg_types = {"this": True, "decimals": False}
4436
4437
4438class RowNumber(Func):
4439    arg_types: t.Dict[str, t.Any] = {}
4440
4441
4442class SafeDivide(Func):
4443    arg_types = {"this": True, "expression": True}
4444
4445
4446class SetAgg(AggFunc):
4447    pass
4448
4449
4450class SHA(Func):
4451    _sql_names = ["SHA", "SHA1"]
4452
4453
4454class SHA2(Func):
4455    _sql_names = ["SHA2"]
4456    arg_types = {"this": True, "length": False}
4457
4458
4459class SortArray(Func):
4460    arg_types = {"this": True, "asc": False}
4461
4462
4463class Split(Func):
4464    arg_types = {"this": True, "expression": True, "limit": False}
4465
4466
4467# Start may be omitted in the case of postgres
4468# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4469class Substring(Func):
4470    arg_types = {"this": True, "start": False, "length": False}
4471
4472
4473class StandardHash(Func):
4474    arg_types = {"this": True, "expression": False}
4475
4476
4477class StrPosition(Func):
4478    arg_types = {
4479        "this": True,
4480        "substr": True,
4481        "position": False,
4482        "instance": False,
4483    }
4484
4485
4486class StrToDate(Func):
4487    arg_types = {"this": True, "format": True}
4488
4489
4490class StrToTime(Func):
4491    arg_types = {"this": True, "format": True, "zone": False}
4492
4493
4494# Spark allows unix_timestamp()
4495# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4496class StrToUnix(Func):
4497    arg_types = {"this": False, "format": False}
4498
4499
4500class NumberToStr(Func):
4501    arg_types = {"this": True, "format": True}
4502
4503
4504class FromBase(Func):
4505    arg_types = {"this": True, "expression": True}
4506
4507
4508class Struct(Func):
4509    arg_types = {"expressions": True}
4510    is_var_len_args = True
4511
4512
4513class StructExtract(Func):
4514    arg_types = {"this": True, "expression": True}
4515
4516
4517class Sum(AggFunc):
4518    pass
4519
4520
4521class Sqrt(Func):
4522    pass
4523
4524
4525class Stddev(AggFunc):
4526    pass
4527
4528
4529class StddevPop(AggFunc):
4530    pass
4531
4532
4533class StddevSamp(AggFunc):
4534    pass
4535
4536
4537class TimeToStr(Func):
4538    arg_types = {"this": True, "format": True}
4539
4540
4541class TimeToTimeStr(Func):
4542    pass
4543
4544
4545class TimeToUnix(Func):
4546    pass
4547
4548
4549class TimeStrToDate(Func):
4550    pass
4551
4552
4553class TimeStrToTime(Func):
4554    pass
4555
4556
4557class TimeStrToUnix(Func):
4558    pass
4559
4560
4561class Trim(Func):
4562    arg_types = {
4563        "this": True,
4564        "expression": False,
4565        "position": False,
4566        "collation": False,
4567    }
4568
4569
4570class TsOrDsAdd(Func, TimeUnit):
4571    arg_types = {"this": True, "expression": True, "unit": False}
4572
4573
4574class TsOrDsToDateStr(Func):
4575    pass
4576
4577
4578class TsOrDsToDate(Func):
4579    arg_types = {"this": True, "format": False}
4580
4581
4582class TsOrDiToDi(Func):
4583    pass
4584
4585
4586class Unhex(Func):
4587    pass
4588
4589
4590class UnixToStr(Func):
4591    arg_types = {"this": True, "format": False}
4592
4593
4594# https://prestodb.io/docs/current/functions/datetime.html
4595# presto has weird zone/hours/minutes
4596class UnixToTime(Func):
4597    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4598
4599    SECONDS = Literal.string("seconds")
4600    MILLIS = Literal.string("millis")
4601    MICROS = Literal.string("micros")
4602
4603
4604class UnixToTimeStr(Func):
4605    pass
4606
4607
4608class Upper(Func):
4609    _sql_names = ["UPPER", "UCASE"]
4610
4611
4612class Variance(AggFunc):
4613    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4614
4615
4616class VariancePop(AggFunc):
4617    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4618
4619
4620class Week(Func):
4621    arg_types = {"this": True, "mode": False}
4622
4623
4624class XMLTable(Func):
4625    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4626
4627
4628class Year(Func):
4629    pass
4630
4631
4632class Use(Expression):
4633    arg_types = {"this": True, "kind": False}
4634
4635
4636class Merge(Expression):
4637    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4638
4639
4640class When(Func):
4641    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4642
4643
4644# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4645# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4646class NextValueFor(Func):
4647    arg_types = {"this": True, "order": False}
4648
4649
4650def _norm_arg(arg):
4651    return arg.lower() if type(arg) is str else arg
4652
4653
4654ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4655
4656
4657# Helpers
4658@t.overload
4659def maybe_parse(
4660    sql_or_expression: ExpOrStr,
4661    *,
4662    into: t.Type[E],
4663    dialect: DialectType = None,
4664    prefix: t.Optional[str] = None,
4665    copy: bool = False,
4666    **opts,
4667) -> E:
4668    ...
4669
4670
4671@t.overload
4672def maybe_parse(
4673    sql_or_expression: str | E,
4674    *,
4675    into: t.Optional[IntoType] = None,
4676    dialect: DialectType = None,
4677    prefix: t.Optional[str] = None,
4678    copy: bool = False,
4679    **opts,
4680) -> E:
4681    ...
4682
4683
4684def maybe_parse(
4685    sql_or_expression: ExpOrStr,
4686    *,
4687    into: t.Optional[IntoType] = None,
4688    dialect: DialectType = None,
4689    prefix: t.Optional[str] = None,
4690    copy: bool = False,
4691    **opts,
4692) -> Expression:
4693    """Gracefully handle a possible string or expression.
4694
4695    Example:
4696        >>> maybe_parse("1")
4697        (LITERAL this: 1, is_string: False)
4698        >>> maybe_parse(to_identifier("x"))
4699        (IDENTIFIER this: x, quoted: False)
4700
4701    Args:
4702        sql_or_expression: the SQL code string or an expression
4703        into: the SQLGlot Expression to parse into
4704        dialect: the dialect used to parse the input expressions (in the case that an
4705            input expression is a SQL string).
4706        prefix: a string to prefix the sql with before it gets parsed
4707            (automatically includes a space)
4708        copy: whether or not to copy the expression.
4709        **opts: other options to use to parse the input expressions (again, in the case
4710            that an input expression is a SQL string).
4711
4712    Returns:
4713        Expression: the parsed or given expression.
4714    """
4715    if isinstance(sql_or_expression, Expression):
4716        if copy:
4717            return sql_or_expression.copy()
4718        return sql_or_expression
4719
4720    if sql_or_expression is None:
4721        raise ParseError(f"SQL cannot be None")
4722
4723    import sqlglot
4724
4725    sql = str(sql_or_expression)
4726    if prefix:
4727        sql = f"{prefix} {sql}"
4728
4729    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4730
4731
4732def _maybe_copy(instance: E, copy: bool = True) -> E:
4733    return instance.copy() if copy else instance
4734
4735
4736def _is_wrong_expression(expression, into):
4737    return isinstance(expression, Expression) and not isinstance(expression, into)
4738
4739
4740def _apply_builder(
4741    expression,
4742    instance,
4743    arg,
4744    copy=True,
4745    prefix=None,
4746    into=None,
4747    dialect=None,
4748    **opts,
4749):
4750    if _is_wrong_expression(expression, into):
4751        expression = into(this=expression)
4752    instance = _maybe_copy(instance, copy)
4753    expression = maybe_parse(
4754        sql_or_expression=expression,
4755        prefix=prefix,
4756        into=into,
4757        dialect=dialect,
4758        **opts,
4759    )
4760    instance.set(arg, expression)
4761    return instance
4762
4763
4764def _apply_child_list_builder(
4765    *expressions,
4766    instance,
4767    arg,
4768    append=True,
4769    copy=True,
4770    prefix=None,
4771    into=None,
4772    dialect=None,
4773    properties=None,
4774    **opts,
4775):
4776    instance = _maybe_copy(instance, copy)
4777    parsed = []
4778    for expression in expressions:
4779        if expression is not None:
4780            if _is_wrong_expression(expression, into):
4781                expression = into(expressions=[expression])
4782
4783            expression = maybe_parse(
4784                expression,
4785                into=into,
4786                dialect=dialect,
4787                prefix=prefix,
4788                **opts,
4789            )
4790            parsed.extend(expression.expressions)
4791
4792    existing = instance.args.get(arg)
4793    if append and existing:
4794        parsed = existing.expressions + parsed
4795
4796    child = into(expressions=parsed)
4797    for k, v in (properties or {}).items():
4798        child.set(k, v)
4799    instance.set(arg, child)
4800
4801    return instance
4802
4803
4804def _apply_list_builder(
4805    *expressions,
4806    instance,
4807    arg,
4808    append=True,
4809    copy=True,
4810    prefix=None,
4811    into=None,
4812    dialect=None,
4813    **opts,
4814):
4815    inst = _maybe_copy(instance, copy)
4816
4817    expressions = [
4818        maybe_parse(
4819            sql_or_expression=expression,
4820            into=into,
4821            prefix=prefix,
4822            dialect=dialect,
4823            **opts,
4824        )
4825        for expression in expressions
4826        if expression is not None
4827    ]
4828
4829    existing_expressions = inst.args.get(arg)
4830    if append and existing_expressions:
4831        expressions = existing_expressions + expressions
4832
4833    inst.set(arg, expressions)
4834    return inst
4835
4836
4837def _apply_conjunction_builder(
4838    *expressions,
4839    instance,
4840    arg,
4841    into=None,
4842    append=True,
4843    copy=True,
4844    dialect=None,
4845    **opts,
4846):
4847    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4848    if not expressions:
4849        return instance
4850
4851    inst = _maybe_copy(instance, copy)
4852
4853    existing = inst.args.get(arg)
4854    if append and existing is not None:
4855        expressions = [existing.this if into else existing] + list(expressions)
4856
4857    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4858
4859    inst.set(arg, into(this=node) if into else node)
4860    return inst
4861
4862
4863def _apply_cte_builder(
4864    instance: E,
4865    alias: ExpOrStr,
4866    as_: ExpOrStr,
4867    recursive: t.Optional[bool] = None,
4868    append: bool = True,
4869    dialect: DialectType = None,
4870    copy: bool = True,
4871    **opts,
4872) -> E:
4873    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4874    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4875    cte = CTE(this=as_expression, alias=alias_expression)
4876    return _apply_child_list_builder(
4877        cte,
4878        instance=instance,
4879        arg="with",
4880        append=append,
4881        copy=copy,
4882        into=With,
4883        properties={"recursive": recursive or False},
4884    )
4885
4886
4887def _combine(
4888    expressions: t.Sequence[t.Optional[ExpOrStr]],
4889    operator: t.Type[Connector],
4890    dialect: DialectType = None,
4891    copy: bool = True,
4892    **opts,
4893) -> Expression:
4894    conditions = [
4895        condition(expression, dialect=dialect, copy=copy, **opts)
4896        for expression in expressions
4897        if expression is not None
4898    ]
4899
4900    this, *rest = conditions
4901    if rest:
4902        this = _wrap(this, Connector)
4903    for expression in rest:
4904        this = operator(this=this, expression=_wrap(expression, Connector))
4905
4906    return this
4907
4908
4909def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4910    return Paren(this=expression) if isinstance(expression, kind) else expression
4911
4912
4913def union(
4914    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4915) -> Union:
4916    """
4917    Initializes a syntax tree from one UNION expression.
4918
4919    Example:
4920        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4921        'SELECT * FROM foo UNION SELECT * FROM bla'
4922
4923    Args:
4924        left: the SQL code string corresponding to the left-hand side.
4925            If an `Expression` instance is passed, it will be used as-is.
4926        right: the SQL code string corresponding to the right-hand side.
4927            If an `Expression` instance is passed, it will be used as-is.
4928        distinct: set the DISTINCT flag if and only if this is true.
4929        dialect: the dialect used to parse the input expression.
4930        opts: other options to use to parse the input expressions.
4931
4932    Returns:
4933        The new Union instance.
4934    """
4935    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4936    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4937
4938    return Union(this=left, expression=right, distinct=distinct)
4939
4940
4941def intersect(
4942    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4943) -> Intersect:
4944    """
4945    Initializes a syntax tree from one INTERSECT expression.
4946
4947    Example:
4948        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4949        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4950
4951    Args:
4952        left: the SQL code string corresponding to the left-hand side.
4953            If an `Expression` instance is passed, it will be used as-is.
4954        right: the SQL code string corresponding to the right-hand side.
4955            If an `Expression` instance is passed, it will be used as-is.
4956        distinct: set the DISTINCT flag if and only if this is true.
4957        dialect: the dialect used to parse the input expression.
4958        opts: other options to use to parse the input expressions.
4959
4960    Returns:
4961        The new Intersect instance.
4962    """
4963    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4964    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4965
4966    return Intersect(this=left, expression=right, distinct=distinct)
4967
4968
4969def except_(
4970    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4971) -> Except:
4972    """
4973    Initializes a syntax tree from one EXCEPT expression.
4974
4975    Example:
4976        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4977        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4978
4979    Args:
4980        left: the SQL code string corresponding to the left-hand side.
4981            If an `Expression` instance is passed, it will be used as-is.
4982        right: the SQL code string corresponding to the right-hand side.
4983            If an `Expression` instance is passed, it will be used as-is.
4984        distinct: set the DISTINCT flag if and only if this is true.
4985        dialect: the dialect used to parse the input expression.
4986        opts: other options to use to parse the input expressions.
4987
4988    Returns:
4989        The new Except instance.
4990    """
4991    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4992    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4993
4994    return Except(this=left, expression=right, distinct=distinct)
4995
4996
4997def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4998    """
4999    Initializes a syntax tree from one or multiple SELECT expressions.
5000
5001    Example:
5002        >>> select("col1", "col2").from_("tbl").sql()
5003        'SELECT col1, col2 FROM tbl'
5004
5005    Args:
5006        *expressions: the SQL code string to parse as the expressions of a
5007            SELECT statement. If an Expression instance is passed, this is used as-is.
5008        dialect: the dialect used to parse the input expressions (in the case that an
5009            input expression is a SQL string).
5010        **opts: other options to use to parse the input expressions (again, in the case
5011            that an input expression is a SQL string).
5012
5013    Returns:
5014        Select: the syntax tree for the SELECT statement.
5015    """
5016    return Select().select(*expressions, dialect=dialect, **opts)
5017
5018
5019def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5020    """
5021    Initializes a syntax tree from a FROM expression.
5022
5023    Example:
5024        >>> from_("tbl").select("col1", "col2").sql()
5025        'SELECT col1, col2 FROM tbl'
5026
5027    Args:
5028        *expression: the SQL code string to parse as the FROM expressions of a
5029            SELECT statement. If an Expression instance is passed, this is used as-is.
5030        dialect: the dialect used to parse the input expression (in the case that the
5031            input expression is a SQL string).
5032        **opts: other options to use to parse the input expressions (again, in the case
5033            that the input expression is a SQL string).
5034
5035    Returns:
5036        Select: the syntax tree for the SELECT statement.
5037    """
5038    return Select().from_(expression, dialect=dialect, **opts)
5039
5040
5041def update(
5042    table: str | Table,
5043    properties: dict,
5044    where: t.Optional[ExpOrStr] = None,
5045    from_: t.Optional[ExpOrStr] = None,
5046    dialect: DialectType = None,
5047    **opts,
5048) -> Update:
5049    """
5050    Creates an update statement.
5051
5052    Example:
5053        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5054        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5055
5056    Args:
5057        *properties: dictionary of properties to set which are
5058            auto converted to sql objects eg None -> NULL
5059        where: sql conditional parsed into a WHERE statement
5060        from_: sql statement parsed into a FROM statement
5061        dialect: the dialect used to parse the input expressions.
5062        **opts: other options to use to parse the input expressions.
5063
5064    Returns:
5065        Update: the syntax tree for the UPDATE statement.
5066    """
5067    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5068    update_expr.set(
5069        "expressions",
5070        [
5071            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5072            for k, v in properties.items()
5073        ],
5074    )
5075    if from_:
5076        update_expr.set(
5077            "from",
5078            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5079        )
5080    if isinstance(where, Condition):
5081        where = Where(this=where)
5082    if where:
5083        update_expr.set(
5084            "where",
5085            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5086        )
5087    return update_expr
5088
5089
5090def delete(
5091    table: ExpOrStr,
5092    where: t.Optional[ExpOrStr] = None,
5093    returning: t.Optional[ExpOrStr] = None,
5094    dialect: DialectType = None,
5095    **opts,
5096) -> Delete:
5097    """
5098    Builds a delete statement.
5099
5100    Example:
5101        >>> delete("my_table", where="id > 1").sql()
5102        'DELETE FROM my_table WHERE id > 1'
5103
5104    Args:
5105        where: sql conditional parsed into a WHERE statement
5106        returning: sql conditional parsed into a RETURNING statement
5107        dialect: the dialect used to parse the input expressions.
5108        **opts: other options to use to parse the input expressions.
5109
5110    Returns:
5111        Delete: the syntax tree for the DELETE statement.
5112    """
5113    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5114    if where:
5115        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5116    if returning:
5117        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5118    return delete_expr
5119
5120
5121def insert(
5122    expression: ExpOrStr,
5123    into: ExpOrStr,
5124    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5125    overwrite: t.Optional[bool] = None,
5126    dialect: DialectType = None,
5127    copy: bool = True,
5128    **opts,
5129) -> Insert:
5130    """
5131    Builds an INSERT statement.
5132
5133    Example:
5134        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5135        'INSERT INTO tbl VALUES (1, 2, 3)'
5136
5137    Args:
5138        expression: the sql string or expression of the INSERT statement
5139        into: the tbl to insert data to.
5140        columns: optionally the table's column names.
5141        overwrite: whether to INSERT OVERWRITE or not.
5142        dialect: the dialect used to parse the input expressions.
5143        copy: whether or not to copy the expression.
5144        **opts: other options to use to parse the input expressions.
5145
5146    Returns:
5147        Insert: the syntax tree for the INSERT statement.
5148    """
5149    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5150    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5151
5152    if columns:
5153        this = _apply_list_builder(
5154            *columns,
5155            instance=Schema(this=this),
5156            arg="expressions",
5157            into=Identifier,
5158            copy=False,
5159            dialect=dialect,
5160            **opts,
5161        )
5162
5163    return Insert(this=this, expression=expr, overwrite=overwrite)
5164
5165
5166def condition(
5167    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5168) -> Condition:
5169    """
5170    Initialize a logical condition expression.
5171
5172    Example:
5173        >>> condition("x=1").sql()
5174        'x = 1'
5175
5176        This is helpful for composing larger logical syntax trees:
5177        >>> where = condition("x=1")
5178        >>> where = where.and_("y=1")
5179        >>> Select().from_("tbl").select("*").where(where).sql()
5180        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5181
5182    Args:
5183        *expression: the SQL code string to parse.
5184            If an Expression instance is passed, this is used as-is.
5185        dialect: the dialect used to parse the input expression (in the case that the
5186            input expression is a SQL string).
5187        copy: Whether or not to copy `expression` (only applies to expressions).
5188        **opts: other options to use to parse the input expressions (again, in the case
5189            that the input expression is a SQL string).
5190
5191    Returns:
5192        The new Condition instance
5193    """
5194    return maybe_parse(
5195        expression,
5196        into=Condition,
5197        dialect=dialect,
5198        copy=copy,
5199        **opts,
5200    )
5201
5202
5203def and_(
5204    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5205) -> Condition:
5206    """
5207    Combine multiple conditions with an AND logical operator.
5208
5209    Example:
5210        >>> and_("x=1", and_("y=1", "z=1")).sql()
5211        'x = 1 AND (y = 1 AND z = 1)'
5212
5213    Args:
5214        *expressions: the SQL code strings to parse.
5215            If an Expression instance is passed, this is used as-is.
5216        dialect: the dialect used to parse the input expression.
5217        copy: whether or not to copy `expressions` (only applies to Expressions).
5218        **opts: other options to use to parse the input expressions.
5219
5220    Returns:
5221        And: the new condition
5222    """
5223    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5224
5225
5226def or_(
5227    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5228) -> Condition:
5229    """
5230    Combine multiple conditions with an OR logical operator.
5231
5232    Example:
5233        >>> or_("x=1", or_("y=1", "z=1")).sql()
5234        'x = 1 OR (y = 1 OR z = 1)'
5235
5236    Args:
5237        *expressions: the SQL code strings to parse.
5238            If an Expression instance is passed, this is used as-is.
5239        dialect: the dialect used to parse the input expression.
5240        copy: whether or not to copy `expressions` (only applies to Expressions).
5241        **opts: other options to use to parse the input expressions.
5242
5243    Returns:
5244        Or: the new condition
5245    """
5246    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5247
5248
5249def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5250    """
5251    Wrap a condition with a NOT operator.
5252
5253    Example:
5254        >>> not_("this_suit='black'").sql()
5255        "NOT this_suit = 'black'"
5256
5257    Args:
5258        expression: the SQL code string to parse.
5259            If an Expression instance is passed, this is used as-is.
5260        dialect: the dialect used to parse the input expression.
5261        copy: whether to copy the expression or not.
5262        **opts: other options to use to parse the input expressions.
5263
5264    Returns:
5265        The new condition.
5266    """
5267    this = condition(
5268        expression,
5269        dialect=dialect,
5270        copy=copy,
5271        **opts,
5272    )
5273    return Not(this=_wrap(this, Connector))
5274
5275
5276def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5277    """
5278    Wrap an expression in parentheses.
5279
5280    Example:
5281        >>> paren("5 + 3").sql()
5282        '(5 + 3)'
5283
5284    Args:
5285        expression: the SQL code string to parse.
5286            If an Expression instance is passed, this is used as-is.
5287        copy: whether to copy the expression or not.
5288
5289    Returns:
5290        The wrapped expression.
5291    """
5292    return Paren(this=maybe_parse(expression, copy=copy))
5293
5294
5295SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5296
5297
5298@t.overload
5299def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5300    ...
5301
5302
5303@t.overload
5304def to_identifier(
5305    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5306) -> Identifier:
5307    ...
5308
5309
5310def to_identifier(name, quoted=None, copy=True):
5311    """Builds an identifier.
5312
5313    Args:
5314        name: The name to turn into an identifier.
5315        quoted: Whether or not force quote the identifier.
5316        copy: Whether or not to copy a passed in Identefier node.
5317
5318    Returns:
5319        The identifier ast node.
5320    """
5321
5322    if name is None:
5323        return None
5324
5325    if isinstance(name, Identifier):
5326        identifier = _maybe_copy(name, copy)
5327    elif isinstance(name, str):
5328        identifier = Identifier(
5329            this=name,
5330            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5331        )
5332    else:
5333        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5334    return identifier
5335
5336
5337INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5338
5339
5340def to_interval(interval: str | Literal) -> Interval:
5341    """Builds an interval expression from a string like '1 day' or '5 months'."""
5342    if isinstance(interval, Literal):
5343        if not interval.is_string:
5344            raise ValueError("Invalid interval string.")
5345
5346        interval = interval.this
5347
5348    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5349
5350    if not interval_parts:
5351        raise ValueError("Invalid interval string.")
5352
5353    return Interval(
5354        this=Literal.string(interval_parts.group(1)),
5355        unit=Var(this=interval_parts.group(2)),
5356    )
5357
5358
5359@t.overload
5360def to_table(sql_path: str | Table, **kwargs) -> Table:
5361    ...
5362
5363
5364@t.overload
5365def to_table(sql_path: None, **kwargs) -> None:
5366    ...
5367
5368
5369def to_table(
5370    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5371) -> t.Optional[Table]:
5372    """
5373    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5374    If a table is passed in then that table is returned.
5375
5376    Args:
5377        sql_path: a `[catalog].[schema].[table]` string.
5378        dialect: the source dialect according to which the table name will be parsed.
5379        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5380
5381    Returns:
5382        A table expression.
5383    """
5384    if sql_path is None or isinstance(sql_path, Table):
5385        return sql_path
5386    if not isinstance(sql_path, str):
5387        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5388
5389    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5390    if table:
5391        for k, v in kwargs.items():
5392            table.set(k, v)
5393
5394    return table
5395
5396
5397def to_column(sql_path: str | Column, **kwargs) -> Column:
5398    """
5399    Create a column from a `[table].[column]` sql path. Schema is optional.
5400
5401    If a column is passed in then that column is returned.
5402
5403    Args:
5404        sql_path: `[table].[column]` string
5405    Returns:
5406        Table: A column expression
5407    """
5408    if sql_path is None or isinstance(sql_path, Column):
5409        return sql_path
5410    if not isinstance(sql_path, str):
5411        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5412    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5413
5414
5415def alias_(
5416    expression: ExpOrStr,
5417    alias: str | Identifier,
5418    table: bool | t.Sequence[str | Identifier] = False,
5419    quoted: t.Optional[bool] = None,
5420    dialect: DialectType = None,
5421    copy: bool = True,
5422    **opts,
5423):
5424    """Create an Alias expression.
5425
5426    Example:
5427        >>> alias_('foo', 'bar').sql()
5428        'foo AS bar'
5429
5430        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5431        '(SELECT 1, 2) AS bar(a, b)'
5432
5433    Args:
5434        expression: the SQL code strings to parse.
5435            If an Expression instance is passed, this is used as-is.
5436        alias: the alias name to use. If the name has
5437            special characters it is quoted.
5438        table: Whether or not to create a table alias, can also be a list of columns.
5439        quoted: whether or not to quote the alias
5440        dialect: the dialect used to parse the input expression.
5441        copy: Whether or not to copy the expression.
5442        **opts: other options to use to parse the input expressions.
5443
5444    Returns:
5445        Alias: the aliased expression
5446    """
5447    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5448    alias = to_identifier(alias, quoted=quoted)
5449
5450    if table:
5451        table_alias = TableAlias(this=alias)
5452        exp.set("alias", table_alias)
5453
5454        if not isinstance(table, bool):
5455            for column in table:
5456                table_alias.append("columns", to_identifier(column, quoted=quoted))
5457
5458        return exp
5459
5460    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5461    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5462    # for the complete Window expression.
5463    #
5464    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5465
5466    if "alias" in exp.arg_types and not isinstance(exp, Window):
5467        exp.set("alias", alias)
5468        return exp
5469    return Alias(this=exp, alias=alias)
5470
5471
5472def subquery(
5473    expression: ExpOrStr,
5474    alias: t.Optional[Identifier | str] = None,
5475    dialect: DialectType = None,
5476    **opts,
5477) -> Select:
5478    """
5479    Build a subquery expression.
5480
5481    Example:
5482        >>> subquery('select x from tbl', 'bar').select('x').sql()
5483        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5484
5485    Args:
5486        expression: the SQL code strings to parse.
5487            If an Expression instance is passed, this is used as-is.
5488        alias: the alias name to use.
5489        dialect: the dialect used to parse the input expression.
5490        **opts: other options to use to parse the input expressions.
5491
5492    Returns:
5493        A new Select instance with the subquery expression included.
5494    """
5495
5496    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5497    return Select().from_(expression, dialect=dialect, **opts)
5498
5499
5500def column(
5501    col: str | Identifier,
5502    table: t.Optional[str | Identifier] = None,
5503    db: t.Optional[str | Identifier] = None,
5504    catalog: t.Optional[str | Identifier] = None,
5505    quoted: t.Optional[bool] = None,
5506) -> Column:
5507    """
5508    Build a Column.
5509
5510    Args:
5511        col: Column name.
5512        table: Table name.
5513        db: Database name.
5514        catalog: Catalog name.
5515        quoted: Whether to force quotes on the column's identifiers.
5516
5517    Returns:
5518        The new Column instance.
5519    """
5520    return Column(
5521        this=to_identifier(col, quoted=quoted),
5522        table=to_identifier(table, quoted=quoted),
5523        db=to_identifier(db, quoted=quoted),
5524        catalog=to_identifier(catalog, quoted=quoted),
5525    )
5526
5527
5528def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5529    """Cast an expression to a data type.
5530
5531    Example:
5532        >>> cast('x + 1', 'int').sql()
5533        'CAST(x + 1 AS INT)'
5534
5535    Args:
5536        expression: The expression to cast.
5537        to: The datatype to cast to.
5538
5539    Returns:
5540        The new Cast instance.
5541    """
5542    expression = maybe_parse(expression, **opts)
5543    return Cast(this=expression, to=DataType.build(to, **opts))
5544
5545
5546def table_(
5547    table: Identifier | str,
5548    db: t.Optional[Identifier | str] = None,
5549    catalog: t.Optional[Identifier | str] = None,
5550    quoted: t.Optional[bool] = None,
5551    alias: t.Optional[Identifier | str] = None,
5552) -> Table:
5553    """Build a Table.
5554
5555    Args:
5556        table: Table name.
5557        db: Database name.
5558        catalog: Catalog name.
5559        quote: Whether to force quotes on the table's identifiers.
5560        alias: Table's alias.
5561
5562    Returns:
5563        The new Table instance.
5564    """
5565    return Table(
5566        this=to_identifier(table, quoted=quoted),
5567        db=to_identifier(db, quoted=quoted),
5568        catalog=to_identifier(catalog, quoted=quoted),
5569        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5570    )
5571
5572
5573def values(
5574    values: t.Iterable[t.Tuple[t.Any, ...]],
5575    alias: t.Optional[str] = None,
5576    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5577) -> Values:
5578    """Build VALUES statement.
5579
5580    Example:
5581        >>> values([(1, '2')]).sql()
5582        "VALUES (1, '2')"
5583
5584    Args:
5585        values: values statements that will be converted to SQL
5586        alias: optional alias
5587        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5588         If either are provided then an alias is also required.
5589
5590    Returns:
5591        Values: the Values expression object
5592    """
5593    if columns and not alias:
5594        raise ValueError("Alias is required when providing columns")
5595
5596    return Values(
5597        expressions=[convert(tup) for tup in values],
5598        alias=(
5599            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5600            if columns
5601            else (TableAlias(this=to_identifier(alias)) if alias else None)
5602        ),
5603    )
5604
5605
5606def var(name: t.Optional[ExpOrStr]) -> Var:
5607    """Build a SQL variable.
5608
5609    Example:
5610        >>> repr(var('x'))
5611        '(VAR this: x)'
5612
5613        >>> repr(var(column('x', table='y')))
5614        '(VAR this: x)'
5615
5616    Args:
5617        name: The name of the var or an expression who's name will become the var.
5618
5619    Returns:
5620        The new variable node.
5621    """
5622    if not name:
5623        raise ValueError("Cannot convert empty name into var.")
5624
5625    if isinstance(name, Expression):
5626        name = name.name
5627    return Var(this=name)
5628
5629
5630def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5631    """Build ALTER TABLE... RENAME... expression
5632
5633    Args:
5634        old_name: The old name of the table
5635        new_name: The new name of the table
5636
5637    Returns:
5638        Alter table expression
5639    """
5640    old_table = to_table(old_name)
5641    new_table = to_table(new_name)
5642    return AlterTable(
5643        this=old_table,
5644        actions=[
5645            RenameTable(this=new_table),
5646        ],
5647    )
5648
5649
5650def convert(value: t.Any, copy: bool = False) -> Expression:
5651    """Convert a python value into an expression object.
5652
5653    Raises an error if a conversion is not possible.
5654
5655    Args:
5656        value: A python object.
5657        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5658
5659    Returns:
5660        Expression: the equivalent expression object.
5661    """
5662    if isinstance(value, Expression):
5663        return _maybe_copy(value, copy)
5664    if isinstance(value, str):
5665        return Literal.string(value)
5666    if isinstance(value, bool):
5667        return Boolean(this=value)
5668    if value is None or (isinstance(value, float) and math.isnan(value)):
5669        return NULL
5670    if isinstance(value, numbers.Number):
5671        return Literal.number(value)
5672    if isinstance(value, datetime.datetime):
5673        datetime_literal = Literal.string(
5674            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5675        )
5676        return TimeStrToTime(this=datetime_literal)
5677    if isinstance(value, datetime.date):
5678        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5679        return DateStrToDate(this=date_literal)
5680    if isinstance(value, tuple):
5681        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5682    if isinstance(value, list):
5683        return Array(expressions=[convert(v, copy=copy) for v in value])
5684    if isinstance(value, dict):
5685        return Map(
5686            keys=[convert(k, copy=copy) for k in value],
5687            values=[convert(v, copy=copy) for v in value.values()],
5688        )
5689    raise ValueError(f"Cannot convert {value}")
5690
5691
5692def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5693    """
5694    Replace children of an expression with the result of a lambda fun(child) -> exp.
5695    """
5696    for k, v in expression.args.items():
5697        is_list_arg = type(v) is list
5698
5699        child_nodes = v if is_list_arg else [v]
5700        new_child_nodes = []
5701
5702        for cn in child_nodes:
5703            if isinstance(cn, Expression):
5704                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5705                    new_child_nodes.append(child_node)
5706                    child_node.parent = expression
5707                    child_node.arg_key = k
5708            else:
5709                new_child_nodes.append(cn)
5710
5711        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5712
5713
5714def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5715    """
5716    Return all table names referenced through columns in an expression.
5717
5718    Example:
5719        >>> import sqlglot
5720        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5721        ['a', 'c']
5722
5723    Args:
5724        expression: expression to find table names.
5725        exclude: a table name to exclude
5726
5727    Returns:
5728        A list of unique names.
5729    """
5730    return {
5731        table
5732        for table in (column.table for column in expression.find_all(Column))
5733        if table and table != exclude
5734    }
5735
5736
5737def table_name(table: Table | str, dialect: DialectType = None) -> str:
5738    """Get the full name of a table as a string.
5739
5740    Args:
5741        table: Table expression node or string.
5742        dialect: The dialect to generate the table name for.
5743
5744    Examples:
5745        >>> from sqlglot import exp, parse_one
5746        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5747        'a.b.c'
5748
5749    Returns:
5750        The table name.
5751    """
5752
5753    table = maybe_parse(table, into=Table)
5754
5755    if not table:
5756        raise ValueError(f"Cannot parse {table}")
5757
5758    return ".".join(
5759        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5760        for part in table.parts
5761    )
5762
5763
5764def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5765    """Replace all tables in expression according to the mapping.
5766
5767    Args:
5768        expression: expression node to be transformed and replaced.
5769        mapping: mapping of table names.
5770        copy: whether or not to copy the expression.
5771
5772    Examples:
5773        >>> from sqlglot import exp, parse_one
5774        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5775        'SELECT * FROM c'
5776
5777    Returns:
5778        The mapped expression.
5779    """
5780
5781    def _replace_tables(node: Expression) -> Expression:
5782        if isinstance(node, Table):
5783            new_name = mapping.get(table_name(node))
5784            if new_name:
5785                return to_table(
5786                    new_name,
5787                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5788                )
5789        return node
5790
5791    return expression.transform(_replace_tables, copy=copy)
5792
5793
5794def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5795    """Replace placeholders in an expression.
5796
5797    Args:
5798        expression: expression node to be transformed and replaced.
5799        args: positional names that will substitute unnamed placeholders in the given order.
5800        kwargs: keyword arguments that will substitute named placeholders.
5801
5802    Examples:
5803        >>> from sqlglot import exp, parse_one
5804        >>> replace_placeholders(
5805        ...     parse_one("select * from :tbl where ? = ?"),
5806        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5807        ... ).sql()
5808        "SELECT * FROM foo WHERE str_col = 'b'"
5809
5810    Returns:
5811        The mapped expression.
5812    """
5813
5814    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5815        if isinstance(node, Placeholder):
5816            if node.name:
5817                new_name = kwargs.get(node.name)
5818                if new_name:
5819                    return convert(new_name)
5820            else:
5821                try:
5822                    return convert(next(args))
5823                except StopIteration:
5824                    pass
5825        return node
5826
5827    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5828
5829
5830def expand(
5831    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5832) -> Expression:
5833    """Transforms an expression by expanding all referenced sources into subqueries.
5834
5835    Examples:
5836        >>> from sqlglot import parse_one
5837        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5838        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5839
5840        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5841        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5842
5843    Args:
5844        expression: The expression to expand.
5845        sources: A dictionary of name to Subqueryables.
5846        copy: Whether or not to copy the expression during transformation. Defaults to True.
5847
5848    Returns:
5849        The transformed expression.
5850    """
5851
5852    def _expand(node: Expression):
5853        if isinstance(node, Table):
5854            name = table_name(node)
5855            source = sources.get(name)
5856            if source:
5857                subquery = source.subquery(node.alias or name)
5858                subquery.comments = [f"source: {name}"]
5859                return subquery.transform(_expand, copy=False)
5860        return node
5861
5862    return expression.transform(_expand, copy=copy)
5863
5864
5865def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5866    """
5867    Returns a Func expression.
5868
5869    Examples:
5870        >>> func("abs", 5).sql()
5871        'ABS(5)'
5872
5873        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5874        'CAST(5 AS DOUBLE)'
5875
5876    Args:
5877        name: the name of the function to build.
5878        args: the args used to instantiate the function of interest.
5879        dialect: the source dialect.
5880        kwargs: the kwargs used to instantiate the function of interest.
5881
5882    Note:
5883        The arguments `args` and `kwargs` are mutually exclusive.
5884
5885    Returns:
5886        An instance of the function of interest, or an anonymous function, if `name` doesn't
5887        correspond to an existing `sqlglot.expressions.Func` class.
5888    """
5889    if args and kwargs:
5890        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5891
5892    from sqlglot.dialects.dialect import Dialect
5893
5894    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5895    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5896
5897    parser = Dialect.get_or_raise(dialect)().parser()
5898    from_args_list = parser.FUNCTIONS.get(name.upper())
5899
5900    if from_args_list:
5901        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5902    else:
5903        kwargs = kwargs or {"expressions": converted}
5904        function = Anonymous(this=name, **kwargs)
5905
5906    for error_message in function.error_messages(converted):
5907        raise ValueError(error_message)
5908
5909    return function
5910
5911
5912def true() -> Boolean:
5913    """
5914    Returns a true Boolean expression.
5915    """
5916    return Boolean(this=True)
5917
5918
5919def false() -> Boolean:
5920    """
5921    Returns a false Boolean expression.
5922    """
5923    return Boolean(this=False)
5924
5925
5926def null() -> Null:
5927    """
5928    Returns a Null expression.
5929    """
5930    return Null()
5931
5932
5933# TODO: deprecate this
5934TRUE = Boolean(this=True)
5935FALSE = Boolean(this=False)
5936NULL = Null()
class Expression:
 55class Expression(metaclass=_Expression):
 56    """
 57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 58    context, such as its child expressions, their names (arg keys), and whether a given child expression
 59    is optional or not.
 60
 61    Attributes:
 62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 63            and representing expressions as strings.
 64        arg_types: determines what arguments (child nodes) are supported by an expression. It
 65            maps arg keys to booleans that indicate whether the corresponding args are optional.
 66        parent: a reference to the parent expression (or None, in case of root expressions).
 67        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 68            uses to refer to it.
 69        comments: a list of comments that are associated with a given expression. This is used in
 70            order to preserve comments when transpiling SQL code.
 71        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 72            optimizer, in order to enable some transformations that require type information.
 73
 74    Example:
 75        >>> class Foo(Expression):
 76        ...     arg_types = {"this": True, "expression": False}
 77
 78        The above definition informs us that Foo is an Expression that requires an argument called
 79        "this" and may also optionally receive an argument called "expression".
 80
 81    Args:
 82        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 83    """
 84
 85    key = "expression"
 86    arg_types = {"this": True}
 87    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 88
 89    def __init__(self, **args: t.Any):
 90        self.args: t.Dict[str, t.Any] = args
 91        self.parent: t.Optional[Expression] = None
 92        self.arg_key: t.Optional[str] = None
 93        self.comments: t.Optional[t.List[str]] = None
 94        self._type: t.Optional[DataType] = None
 95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 96        self._hash: t.Optional[int] = None
 97
 98        for arg_key, value in self.args.items():
 99            self._set_parent(arg_key, value)
100
101    def __eq__(self, other) -> bool:
102        return type(self) is type(other) and hash(self) == hash(other)
103
104    @property
105    def hashable_args(self) -> t.Any:
106        return frozenset(
107            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
108            for k, v in self.args.items()
109            if not (v is None or v is False or (type(v) is list and not v))
110        )
111
112    def __hash__(self) -> int:
113        if self._hash is not None:
114            return self._hash
115
116        return hash((self.__class__, self.hashable_args))
117
118    @property
119    def this(self):
120        """
121        Retrieves the argument with key "this".
122        """
123        return self.args.get("this")
124
125    @property
126    def expression(self):
127        """
128        Retrieves the argument with key "expression".
129        """
130        return self.args.get("expression")
131
132    @property
133    def expressions(self):
134        """
135        Retrieves the argument with key "expressions".
136        """
137        return self.args.get("expressions") or []
138
139    def text(self, key) -> str:
140        """
141        Returns a textual representation of the argument corresponding to "key". This can only be used
142        for args that are strings or leaf Expression instances, such as identifiers and literals.
143        """
144        field = self.args.get(key)
145        if isinstance(field, str):
146            return field
147        if isinstance(field, (Identifier, Literal, Var)):
148            return field.this
149        if isinstance(field, (Star, Null)):
150            return field.name
151        return ""
152
153    @property
154    def is_string(self) -> bool:
155        """
156        Checks whether a Literal expression is a string.
157        """
158        return isinstance(self, Literal) and self.args["is_string"]
159
160    @property
161    def is_number(self) -> bool:
162        """
163        Checks whether a Literal expression is a number.
164        """
165        return isinstance(self, Literal) and not self.args["is_string"]
166
167    @property
168    def is_int(self) -> bool:
169        """
170        Checks whether a Literal expression is an integer.
171        """
172        if self.is_number:
173            try:
174                int(self.name)
175                return True
176            except ValueError:
177                pass
178        return False
179
180    @property
181    def is_star(self) -> bool:
182        """Checks whether an expression is a star."""
183        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
184
185    @property
186    def alias(self) -> str:
187        """
188        Returns the alias of the expression, or an empty string if it's not aliased.
189        """
190        if isinstance(self.args.get("alias"), TableAlias):
191            return self.args["alias"].name
192        return self.text("alias")
193
194    @property
195    def name(self) -> str:
196        return self.text("this")
197
198    @property
199    def alias_or_name(self) -> str:
200        return self.alias or self.name
201
202    @property
203    def output_name(self) -> str:
204        """
205        Name of the output column if this expression is a selection.
206
207        If the Expression has no output name, an empty string is returned.
208
209        Example:
210            >>> from sqlglot import parse_one
211            >>> parse_one("SELECT a").expressions[0].output_name
212            'a'
213            >>> parse_one("SELECT b AS c").expressions[0].output_name
214            'c'
215            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
216            ''
217        """
218        return ""
219
220    @property
221    def type(self) -> t.Optional[DataType]:
222        return self._type
223
224    @type.setter
225    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
226        if dtype and not isinstance(dtype, DataType):
227            dtype = DataType.build(dtype)
228        self._type = dtype  # type: ignore
229
230    @property
231    def meta(self) -> t.Dict[str, t.Any]:
232        if self._meta is None:
233            self._meta = {}
234        return self._meta
235
236    def __deepcopy__(self, memo):
237        copy = self.__class__(**deepcopy(self.args))
238        if self.comments is not None:
239            copy.comments = deepcopy(self.comments)
240
241        if self._type is not None:
242            copy._type = self._type.copy()
243
244        if self._meta is not None:
245            copy._meta = deepcopy(self._meta)
246
247        return copy
248
249    def copy(self):
250        """
251        Returns a deep copy of the expression.
252        """
253        new = deepcopy(self)
254        new.parent = self.parent
255        return new
256
257    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
258        if self.comments is None:
259            self.comments = []
260        if comments:
261            self.comments.extend(comments)
262
263    def append(self, arg_key: str, value: t.Any) -> None:
264        """
265        Appends value to arg_key if it's a list or sets it as a new list.
266
267        Args:
268            arg_key (str): name of the list expression arg
269            value (Any): value to append to the list
270        """
271        if not isinstance(self.args.get(arg_key), list):
272            self.args[arg_key] = []
273        self.args[arg_key].append(value)
274        self._set_parent(arg_key, value)
275
276    def set(self, arg_key: str, value: t.Any) -> None:
277        """
278        Sets arg_key to value.
279
280        Args:
281            arg_key: name of the expression arg.
282            value: value to set the arg to.
283        """
284        if value is None:
285            self.args.pop(arg_key, None)
286            return
287
288        self.args[arg_key] = value
289        self._set_parent(arg_key, value)
290
291    def _set_parent(self, arg_key: str, value: t.Any) -> None:
292        if hasattr(value, "parent"):
293            value.parent = self
294            value.arg_key = arg_key
295        elif type(value) is list:
296            for v in value:
297                if hasattr(v, "parent"):
298                    v.parent = self
299                    v.arg_key = arg_key
300
301    @property
302    def depth(self) -> int:
303        """
304        Returns the depth of this tree.
305        """
306        if self.parent:
307            return self.parent.depth + 1
308        return 0
309
310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
311        """Yields the key and expression for all arguments, exploding list args."""
312        for k, vs in self.args.items():
313            if type(vs) is list:
314                for v in vs:
315                    if hasattr(v, "parent"):
316                        yield k, v
317            else:
318                if hasattr(vs, "parent"):
319                    yield k, vs
320
321    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
322        """
323        Returns the first node in this tree which matches at least one of
324        the specified types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)
334
335    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
343
344        Returns:
345            The generator object.
346        """
347        for expression, *_ in self.walk(bfs=bfs):
348            if isinstance(expression, expression_types):
349                yield expression
350
351    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
352        """
353        Returns a nearest parent matching expression_types.
354
355        Args:
356            expression_types: the expression type(s) to match.
357
358        Returns:
359            The parent node.
360        """
361        ancestor = self.parent
362        while ancestor and not isinstance(ancestor, expression_types):
363            ancestor = ancestor.parent
364        return t.cast(E, ancestor)
365
366    @property
367    def parent_select(self) -> t.Optional[Select]:
368        """
369        Returns the parent select statement.
370        """
371        return self.find_ancestor(Select)
372
373    @property
374    def same_parent(self) -> bool:
375        """Returns if the parent is the same class as itself."""
376        return type(self.parent) is self.__class__
377
378    def root(self) -> Expression:
379        """
380        Returns the root expression of this tree.
381        """
382        expression = self
383        while expression.parent:
384            expression = expression.parent
385        return expression
386
387    def walk(self, bfs=True, prune=None):
388        """
389        Returns a generator object which visits all nodes in this tree.
390
391        Args:
392            bfs (bool): if set to True the BFS traversal order will be applied,
393                otherwise the DFS traversal will be used instead.
394            prune ((node, parent, arg_key) -> bool): callable that returns True if
395                the generator should stop traversing this branch of the tree.
396
397        Returns:
398            the generator object.
399        """
400        if bfs:
401            yield from self.bfs(prune=prune)
402        else:
403            yield from self.dfs(prune=prune)
404
405    def dfs(self, parent=None, key=None, prune=None):
406        """
407        Returns a generator object which visits all nodes in this tree in
408        the DFS (Depth-first) order.
409
410        Returns:
411            The generator object.
412        """
413        parent = parent or self.parent
414        yield self, parent, key
415        if prune and prune(self, parent, key):
416            return
417
418        for k, v in self.iter_expressions():
419            yield from v.dfs(self, k, prune)
420
421    def bfs(self, prune=None):
422        """
423        Returns a generator object which visits all nodes in this tree in
424        the BFS (Breadth-first) order.
425
426        Returns:
427            The generator object.
428        """
429        queue = deque([(self, self.parent, None)])
430
431        while queue:
432            item, parent, key = queue.popleft()
433
434            yield item, parent, key
435            if prune and prune(item, parent, key):
436                continue
437
438            for k, v in item.iter_expressions():
439                queue.append((v, item, k))
440
441    def unnest(self):
442        """
443        Returns the first non parenthesis child or self.
444        """
445        expression = self
446        while type(expression) is Paren:
447            expression = expression.this
448        return expression
449
450    def unalias(self):
451        """
452        Returns the inner expression if this is an Alias.
453        """
454        if isinstance(self, Alias):
455            return self.this
456        return self
457
458    def unnest_operands(self):
459        """
460        Returns unnested operands as a tuple.
461        """
462        return tuple(arg.unnest() for _, arg in self.iter_expressions())
463
464    def flatten(self, unnest=True):
465        """
466        Returns a generator which yields child nodes who's parents are the same class.
467
468        A AND B AND C -> [A, B, C]
469        """
470        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
471            if not type(node) is self.__class__:
472                yield node.unnest() if unnest else node
473
474    def __str__(self) -> str:
475        return self.sql()
476
477    def __repr__(self) -> str:
478        return self._to_s()
479
480    def sql(self, dialect: DialectType = None, **opts) -> str:
481        """
482        Returns SQL string representation of this tree.
483
484        Args:
485            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
486            opts: other `sqlglot.generator.Generator` options.
487
488        Returns:
489            The SQL string.
490        """
491        from sqlglot.dialects import Dialect
492
493        return Dialect.get_or_raise(dialect)().generate(self, **opts)
494
495    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
496        indent = "" if not level else "\n"
497        indent += "".join(["  "] * level)
498        left = f"({self.key.upper()} "
499
500        args: t.Dict[str, t.Any] = {
501            k: ", ".join(
502                v._to_s(hide_missing=hide_missing, level=level + 1)
503                if hasattr(v, "_to_s")
504                else str(v)
505                for v in ensure_list(vs)
506                if v is not None
507            )
508            for k, vs in self.args.items()
509        }
510        args["comments"] = self.comments
511        args["type"] = self.type
512        args = {k: v for k, v in args.items() if v or not hide_missing}
513
514        right = ", ".join(f"{k}: {v}" for k, v in args.items())
515        right += ")"
516
517        return indent + left + right
518
519    def transform(self, fun, *args, copy=True, **kwargs):
520        """
521        Recursively visits all tree nodes (excluding already transformed ones)
522        and applies the given transformation function to each node.
523
524        Args:
525            fun (function): a function which takes a node as an argument and returns a
526                new transformed node or the same node without modifications. If the function
527                returns None, then the corresponding node will be removed from the syntax tree.
528            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
529                modified in place.
530
531        Returns:
532            The transformed tree.
533        """
534        node = self.copy() if copy else self
535        new_node = fun(node, *args, **kwargs)
536
537        if new_node is None or not isinstance(new_node, Expression):
538            return new_node
539        if new_node is not node:
540            new_node.parent = node.parent
541            return new_node
542
543        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
544        return new_node
545
546    @t.overload
547    def replace(self, expression: E) -> E:
548        ...
549
550    @t.overload
551    def replace(self, expression: None) -> None:
552        ...
553
554    def replace(self, expression):
555        """
556        Swap out this expression with a new expression.
557
558        For example::
559
560            >>> tree = Select().select("x").from_("tbl")
561            >>> tree.find(Column).replace(Column(this="y"))
562            (COLUMN this: y)
563            >>> tree.sql()
564            'SELECT y FROM tbl'
565
566        Args:
567            expression: new node
568
569        Returns:
570            The new expression or expressions.
571        """
572        if not self.parent:
573            return expression
574
575        parent = self.parent
576        self.parent = None
577
578        replace_children(parent, lambda child: expression if child is self else child)
579        return expression
580
581    def pop(self: E) -> E:
582        """
583        Remove this expression from its AST.
584
585        Returns:
586            The popped expression.
587        """
588        self.replace(None)
589        return self
590
591    def assert_is(self, type_: t.Type[E]) -> E:
592        """
593        Assert that this `Expression` is an instance of `type_`.
594
595        If it is NOT an instance of `type_`, this raises an assertion error.
596        Otherwise, this returns this expression.
597
598        Examples:
599            This is useful for type security in chained expressions:
600
601            >>> import sqlglot
602            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
603            'SELECT x, z FROM y'
604        """
605        assert isinstance(self, type_)
606        return self
607
608    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
609        """
610        Checks if this expression is valid (e.g. all mandatory args are set).
611
612        Args:
613            args: a sequence of values that were used to instantiate a Func expression. This is used
614                to check that the provided arguments don't exceed the function argument limit.
615
616        Returns:
617            A list of error messages for all possible errors that were found.
618        """
619        errors: t.List[str] = []
620
621        for k in self.args:
622            if k not in self.arg_types:
623                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
624        for k, mandatory in self.arg_types.items():
625            v = self.args.get(k)
626            if mandatory and (v is None or (isinstance(v, list) and not v)):
627                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
628
629        if (
630            args
631            and isinstance(self, Func)
632            and len(args) > len(self.arg_types)
633            and not self.is_var_len_args
634        ):
635            errors.append(
636                f"The number of provided arguments ({len(args)}) is greater than "
637                f"the maximum number of supported arguments ({len(self.arg_types)})"
638            )
639
640        return errors
641
642    def dump(self):
643        """
644        Dump this Expression to a JSON-serializable dict.
645        """
646        from sqlglot.serde import dump
647
648        return dump(self)
649
650    @classmethod
651    def load(cls, obj):
652        """
653        Load a dict (as returned by `Expression.dump`) into an Expression instance.
654        """
655        from sqlglot.serde import load
656
657        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
139    def text(self, key) -> str:
140        """
141        Returns a textual representation of the argument corresponding to "key". This can only be used
142        for args that are strings or leaf Expression instances, such as identifiers and literals.
143        """
144        field = self.args.get(key)
145        if isinstance(field, str):
146            return field
147        if isinstance(field, (Identifier, Literal, Var)):
148            return field.this
149        if isinstance(field, (Star, Null)):
150            return field.name
151        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

name: str
alias_or_name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
249    def copy(self):
250        """
251        Returns a deep copy of the expression.
252        """
253        new = deepcopy(self)
254        new.parent = self.parent
255        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
257    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
258        if self.comments is None:
259            self.comments = []
260        if comments:
261            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
263    def append(self, arg_key: str, value: t.Any) -> None:
264        """
265        Appends value to arg_key if it's a list or sets it as a new list.
266
267        Args:
268            arg_key (str): name of the list expression arg
269            value (Any): value to append to the list
270        """
271        if not isinstance(self.args.get(arg_key), list):
272            self.args[arg_key] = []
273        self.args[arg_key].append(value)
274        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
276    def set(self, arg_key: str, value: t.Any) -> None:
277        """
278        Sets arg_key to value.
279
280        Args:
281            arg_key: name of the expression arg.
282            value: value to set the arg to.
283        """
284        if value is None:
285            self.args.pop(arg_key, None)
286            return
287
288        self.args[arg_key] = value
289        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
311        """Yields the key and expression for all arguments, exploding list args."""
312        for k, vs in self.args.items():
313            if type(vs) is list:
314                for v in vs:
315                    if hasattr(v, "parent"):
316                        yield k, v
317            else:
318                if hasattr(vs, "parent"):
319                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
321    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
322        """
323        Returns the first node in this tree which matches at least one of
324        the specified types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
343
344        Returns:
345            The generator object.
346        """
347        for expression, *_ in self.walk(bfs=bfs):
348            if isinstance(expression, expression_types):
349                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
351    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
352        """
353        Returns a nearest parent matching expression_types.
354
355        Args:
356            expression_types: the expression type(s) to match.
357
358        Returns:
359            The parent node.
360        """
361        ancestor = self.parent
362        while ancestor and not isinstance(ancestor, expression_types):
363            ancestor = ancestor.parent
364        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
378    def root(self) -> Expression:
379        """
380        Returns the root expression of this tree.
381        """
382        expression = self
383        while expression.parent:
384            expression = expression.parent
385        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
387    def walk(self, bfs=True, prune=None):
388        """
389        Returns a generator object which visits all nodes in this tree.
390
391        Args:
392            bfs (bool): if set to True the BFS traversal order will be applied,
393                otherwise the DFS traversal will be used instead.
394            prune ((node, parent, arg_key) -> bool): callable that returns True if
395                the generator should stop traversing this branch of the tree.
396
397        Returns:
398            the generator object.
399        """
400        if bfs:
401            yield from self.bfs(prune=prune)
402        else:
403            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
405    def dfs(self, parent=None, key=None, prune=None):
406        """
407        Returns a generator object which visits all nodes in this tree in
408        the DFS (Depth-first) order.
409
410        Returns:
411            The generator object.
412        """
413        parent = parent or self.parent
414        yield self, parent, key
415        if prune and prune(self, parent, key):
416            return
417
418        for k, v in self.iter_expressions():
419            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
421    def bfs(self, prune=None):
422        """
423        Returns a generator object which visits all nodes in this tree in
424        the BFS (Breadth-first) order.
425
426        Returns:
427            The generator object.
428        """
429        queue = deque([(self, self.parent, None)])
430
431        while queue:
432            item, parent, key = queue.popleft()
433
434            yield item, parent, key
435            if prune and prune(item, parent, key):
436                continue
437
438            for k, v in item.iter_expressions():
439                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
441    def unnest(self):
442        """
443        Returns the first non parenthesis child or self.
444        """
445        expression = self
446        while type(expression) is Paren:
447            expression = expression.this
448        return expression

Returns the first non parenthesis child or self.

def unalias(self):
450    def unalias(self):
451        """
452        Returns the inner expression if this is an Alias.
453        """
454        if isinstance(self, Alias):
455            return self.this
456        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
458    def unnest_operands(self):
459        """
460        Returns unnested operands as a tuple.
461        """
462        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
464    def flatten(self, unnest=True):
465        """
466        Returns a generator which yields child nodes who's parents are the same class.
467
468        A AND B AND C -> [A, B, C]
469        """
470        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
471            if not type(node) is self.__class__:
472                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
480    def sql(self, dialect: DialectType = None, **opts) -> str:
481        """
482        Returns SQL string representation of this tree.
483
484        Args:
485            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
486            opts: other `sqlglot.generator.Generator` options.
487
488        Returns:
489            The SQL string.
490        """
491        from sqlglot.dialects import Dialect
492
493        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
519    def transform(self, fun, *args, copy=True, **kwargs):
520        """
521        Recursively visits all tree nodes (excluding already transformed ones)
522        and applies the given transformation function to each node.
523
524        Args:
525            fun (function): a function which takes a node as an argument and returns a
526                new transformed node or the same node without modifications. If the function
527                returns None, then the corresponding node will be removed from the syntax tree.
528            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
529                modified in place.
530
531        Returns:
532            The transformed tree.
533        """
534        node = self.copy() if copy else self
535        new_node = fun(node, *args, **kwargs)
536
537        if new_node is None or not isinstance(new_node, Expression):
538            return new_node
539        if new_node is not node:
540            new_node.parent = node.parent
541            return new_node
542
543        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
544        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
554    def replace(self, expression):
555        """
556        Swap out this expression with a new expression.
557
558        For example::
559
560            >>> tree = Select().select("x").from_("tbl")
561            >>> tree.find(Column).replace(Column(this="y"))
562            (COLUMN this: y)
563            >>> tree.sql()
564            'SELECT y FROM tbl'
565
566        Args:
567            expression: new node
568
569        Returns:
570            The new expression or expressions.
571        """
572        if not self.parent:
573            return expression
574
575        parent = self.parent
576        self.parent = None
577
578        replace_children(parent, lambda child: expression if child is self else child)
579        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
581    def pop(self: E) -> E:
582        """
583        Remove this expression from its AST.
584
585        Returns:
586            The popped expression.
587        """
588        self.replace(None)
589        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
591    def assert_is(self, type_: t.Type[E]) -> E:
592        """
593        Assert that this `Expression` is an instance of `type_`.
594
595        If it is NOT an instance of `type_`, this raises an assertion error.
596        Otherwise, this returns this expression.
597
598        Examples:
599            This is useful for type security in chained expressions:
600
601            >>> import sqlglot
602            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
603            'SELECT x, z FROM y'
604        """
605        assert isinstance(self, type_)
606        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
608    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
609        """
610        Checks if this expression is valid (e.g. all mandatory args are set).
611
612        Args:
613            args: a sequence of values that were used to instantiate a Func expression. This is used
614                to check that the provided arguments don't exceed the function argument limit.
615
616        Returns:
617            A list of error messages for all possible errors that were found.
618        """
619        errors: t.List[str] = []
620
621        for k in self.args:
622            if k not in self.arg_types:
623                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
624        for k, mandatory in self.arg_types.items():
625            v = self.args.get(k)
626            if mandatory and (v is None or (isinstance(v, list) and not v)):
627                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
628
629        if (
630            args
631            and isinstance(self, Func)
632            and len(args) > len(self.arg_types)
633            and not self.is_var_len_args
634        ):
635            errors.append(
636                f"The number of provided arguments ({len(args)}) is greater than "
637                f"the maximum number of supported arguments ({len(self.arg_types)})"
638            )
639
640        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
642    def dump(self):
643        """
644        Dump this Expression to a JSON-serializable dict.
645        """
646        from sqlglot.serde import dump
647
648        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
650    @classmethod
651    def load(cls, obj):
652        """
653        Load a dict (as returned by `Expression.dump`) into an Expression instance.
654        """
655        from sqlglot.serde import load
656
657        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

IntoType = typing.Union[str, typing.Type[sqlglot.expressions.Expression], typing.Collection[typing.Union[str, typing.Type[sqlglot.expressions.Expression]]]]
ExpOrStr = typing.Union[str, sqlglot.expressions.Expression]
class Condition(Expression):
668class Condition(Expression):
669    def and_(
670        self,
671        *expressions: t.Optional[ExpOrStr],
672        dialect: DialectType = None,
673        copy: bool = True,
674        **opts,
675    ) -> Condition:
676        """
677        AND this condition with one or multiple expressions.
678
679        Example:
680            >>> condition("x=1").and_("y=1").sql()
681            'x = 1 AND y = 1'
682
683        Args:
684            *expressions: the SQL code strings to parse.
685                If an `Expression` instance is passed, it will be used as-is.
686            dialect: the dialect used to parse the input expression.
687            copy: whether or not to copy the involved expressions (only applies to Expressions).
688            opts: other options to use to parse the input expressions.
689
690        Returns:
691            The new And condition.
692        """
693        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
694
695    def or_(
696        self,
697        *expressions: t.Optional[ExpOrStr],
698        dialect: DialectType = None,
699        copy: bool = True,
700        **opts,
701    ) -> Condition:
702        """
703        OR this condition with one or multiple expressions.
704
705        Example:
706            >>> condition("x=1").or_("y=1").sql()
707            'x = 1 OR y = 1'
708
709        Args:
710            *expressions: the SQL code strings to parse.
711                If an `Expression` instance is passed, it will be used as-is.
712            dialect: the dialect used to parse the input expression.
713            copy: whether or not to copy the involved expressions (only applies to Expressions).
714            opts: other options to use to parse the input expressions.
715
716        Returns:
717            The new Or condition.
718        """
719        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
720
721    def not_(self, copy: bool = True):
722        """
723        Wrap this condition with NOT.
724
725        Example:
726            >>> condition("x=1").not_().sql()
727            'NOT x = 1'
728
729        Args:
730            copy: whether or not to copy this object.
731
732        Returns:
733            The new Not instance.
734        """
735        return not_(self, copy=copy)
736
737    def as_(
738        self,
739        alias: str | Identifier,
740        quoted: t.Optional[bool] = None,
741        dialect: DialectType = None,
742        copy: bool = True,
743        **opts,
744    ) -> Alias:
745        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
746
747    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
748        this = self.copy()
749        other = convert(other, copy=True)
750        if not isinstance(this, klass) and not isinstance(other, klass):
751            this = _wrap(this, Binary)
752            other = _wrap(other, Binary)
753        if reverse:
754            return klass(this=other, expression=this)
755        return klass(this=this, expression=other)
756
757    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
758        return Bracket(
759            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
760        )
761
762    def isin(
763        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
764    ) -> In:
765        return In(
766            this=_maybe_copy(self, copy),
767            expressions=[convert(e, copy=copy) for e in expressions],
768            query=maybe_parse(query, copy=copy, **opts) if query else None,
769        )
770
771    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
772        return Between(
773            this=_maybe_copy(self, copy),
774            low=convert(low, copy=copy, **opts),
775            high=convert(high, copy=copy, **opts),
776        )
777
778    def is_(self, other: ExpOrStr) -> Is:
779        return self._binop(Is, other)
780
781    def like(self, other: ExpOrStr) -> Like:
782        return self._binop(Like, other)
783
784    def ilike(self, other: ExpOrStr) -> ILike:
785        return self._binop(ILike, other)
786
787    def eq(self, other: t.Any) -> EQ:
788        return self._binop(EQ, other)
789
790    def neq(self, other: t.Any) -> NEQ:
791        return self._binop(NEQ, other)
792
793    def rlike(self, other: ExpOrStr) -> RegexpLike:
794        return self._binop(RegexpLike, other)
795
796    def __lt__(self, other: t.Any) -> LT:
797        return self._binop(LT, other)
798
799    def __le__(self, other: t.Any) -> LTE:
800        return self._binop(LTE, other)
801
802    def __gt__(self, other: t.Any) -> GT:
803        return self._binop(GT, other)
804
805    def __ge__(self, other: t.Any) -> GTE:
806        return self._binop(GTE, other)
807
808    def __add__(self, other: t.Any) -> Add:
809        return self._binop(Add, other)
810
811    def __radd__(self, other: t.Any) -> Add:
812        return self._binop(Add, other, reverse=True)
813
814    def __sub__(self, other: t.Any) -> Sub:
815        return self._binop(Sub, other)
816
817    def __rsub__(self, other: t.Any) -> Sub:
818        return self._binop(Sub, other, reverse=True)
819
820    def __mul__(self, other: t.Any) -> Mul:
821        return self._binop(Mul, other)
822
823    def __rmul__(self, other: t.Any) -> Mul:
824        return self._binop(Mul, other, reverse=True)
825
826    def __truediv__(self, other: t.Any) -> Div:
827        return self._binop(Div, other)
828
829    def __rtruediv__(self, other: t.Any) -> Div:
830        return self._binop(Div, other, reverse=True)
831
832    def __floordiv__(self, other: t.Any) -> IntDiv:
833        return self._binop(IntDiv, other)
834
835    def __rfloordiv__(self, other: t.Any) -> IntDiv:
836        return self._binop(IntDiv, other, reverse=True)
837
838    def __mod__(self, other: t.Any) -> Mod:
839        return self._binop(Mod, other)
840
841    def __rmod__(self, other: t.Any) -> Mod:
842        return self._binop(Mod, other, reverse=True)
843
844    def __pow__(self, other: t.Any) -> Pow:
845        return self._binop(Pow, other)
846
847    def __rpow__(self, other: t.Any) -> Pow:
848        return self._binop(Pow, other, reverse=True)
849
850    def __and__(self, other: t.Any) -> And:
851        return self._binop(And, other)
852
853    def __rand__(self, other: t.Any) -> And:
854        return self._binop(And, other, reverse=True)
855
856    def __or__(self, other: t.Any) -> Or:
857        return self._binop(Or, other)
858
859    def __ror__(self, other: t.Any) -> Or:
860        return self._binop(Or, other, reverse=True)
861
862    def __neg__(self) -> Neg:
863        return Neg(this=_wrap(self.copy(), Binary))
864
865    def __invert__(self) -> Not:
866        return not_(self.copy())
def and_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
669    def and_(
670        self,
671        *expressions: t.Optional[ExpOrStr],
672        dialect: DialectType = None,
673        copy: bool = True,
674        **opts,
675    ) -> Condition:
676        """
677        AND this condition with one or multiple expressions.
678
679        Example:
680            >>> condition("x=1").and_("y=1").sql()
681            'x = 1 AND y = 1'
682
683        Args:
684            *expressions: the SQL code strings to parse.
685                If an `Expression` instance is passed, it will be used as-is.
686            dialect: the dialect used to parse the input expression.
687            copy: whether or not to copy the involved expressions (only applies to Expressions).
688            opts: other options to use to parse the input expressions.
689
690        Returns:
691            The new And condition.
692        """
693        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
695    def or_(
696        self,
697        *expressions: t.Optional[ExpOrStr],
698        dialect: DialectType = None,
699        copy: bool = True,
700        **opts,
701    ) -> Condition:
702        """
703        OR this condition with one or multiple expressions.
704
705        Example:
706            >>> condition("x=1").or_("y=1").sql()
707            'x = 1 OR y = 1'
708
709        Args:
710            *expressions: the SQL code strings to parse.
711                If an `Expression` instance is passed, it will be used as-is.
712            dialect: the dialect used to parse the input expression.
713            copy: whether or not to copy the involved expressions (only applies to Expressions).
714            opts: other options to use to parse the input expressions.
715
716        Returns:
717            The new Or condition.
718        """
719        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
721    def not_(self, copy: bool = True):
722        """
723        Wrap this condition with NOT.
724
725        Example:
726            >>> condition("x=1").not_().sql()
727            'NOT x = 1'
728
729        Args:
730            copy: whether or not to copy this object.
731
732        Returns:
733            The new Not instance.
734        """
735        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether or not to copy this object.
Returns:

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
737    def as_(
738        self,
739        alias: str | Identifier,
740        quoted: t.Optional[bool] = None,
741        dialect: DialectType = None,
742        copy: bool = True,
743        **opts,
744    ) -> Alias:
745        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
762    def isin(
763        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
764    ) -> In:
765        return In(
766            this=_maybe_copy(self, copy),
767            expressions=[convert(e, copy=copy) for e in expressions],
768            query=maybe_parse(query, copy=copy, **opts) if query else None,
769        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
771    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
772        return Between(
773            this=_maybe_copy(self, copy),
774            low=convert(low, copy=copy, **opts),
775            high=convert(high, copy=copy, **opts),
776        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
778    def is_(self, other: ExpOrStr) -> Is:
779        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
781    def like(self, other: ExpOrStr) -> Like:
782        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
784    def ilike(self, other: ExpOrStr) -> ILike:
785        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
787    def eq(self, other: t.Any) -> EQ:
788        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
790    def neq(self, other: t.Any) -> NEQ:
791        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
793    def rlike(self, other: ExpOrStr) -> RegexpLike:
794        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
869class Predicate(Condition):
870    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
873class DerivedTable(Expression):
874    @property
875    def alias_column_names(self) -> t.List[str]:
876        table_alias = self.args.get("alias")
877        if not table_alias:
878            return []
879        return [c.name for c in table_alias.args.get("columns") or []]
880
881    @property
882    def selects(self):
883        return self.this.selects if isinstance(self.this, Subqueryable) else []
884
885    @property
886    def named_selects(self):
887        return [select.output_name for select in self.selects]
alias_column_names: List[str]
selects
named_selects
key = 'derivedtable'
class Unionable(Expression):
890class Unionable(Expression):
891    def union(
892        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
893    ) -> Unionable:
894        """
895        Builds a UNION expression.
896
897        Example:
898            >>> import sqlglot
899            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
900            'SELECT * FROM foo UNION SELECT * FROM bla'
901
902        Args:
903            expression: the SQL code string.
904                If an `Expression` instance is passed, it will be used as-is.
905            distinct: set the DISTINCT flag if and only if this is true.
906            dialect: the dialect used to parse the input expression.
907            opts: other options to use to parse the input expressions.
908
909        Returns:
910            The new Union expression.
911        """
912        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
913
914    def intersect(
915        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
916    ) -> Unionable:
917        """
918        Builds an INTERSECT expression.
919
920        Example:
921            >>> import sqlglot
922            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
923            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
924
925        Args:
926            expression: the SQL code string.
927                If an `Expression` instance is passed, it will be used as-is.
928            distinct: set the DISTINCT flag if and only if this is true.
929            dialect: the dialect used to parse the input expression.
930            opts: other options to use to parse the input expressions.
931
932        Returns:
933            The new Intersect expression.
934        """
935        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
936
937    def except_(
938        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
939    ) -> Unionable:
940        """
941        Builds an EXCEPT expression.
942
943        Example:
944            >>> import sqlglot
945            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
946            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
947
948        Args:
949            expression: the SQL code string.
950                If an `Expression` instance is passed, it will be used as-is.
951            distinct: set the DISTINCT flag if and only if this is true.
952            dialect: the dialect used to parse the input expression.
953            opts: other options to use to parse the input expressions.
954
955        Returns:
956            The new Except expression.
957        """
958        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
891    def union(
892        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
893    ) -> Unionable:
894        """
895        Builds a UNION expression.
896
897        Example:
898            >>> import sqlglot
899            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
900            'SELECT * FROM foo UNION SELECT * FROM bla'
901
902        Args:
903            expression: the SQL code string.
904                If an `Expression` instance is passed, it will be used as-is.
905            distinct: set the DISTINCT flag if and only if this is true.
906            dialect: the dialect used to parse the input expression.
907            opts: other options to use to parse the input expressions.
908
909        Returns:
910            The new Union expression.
911        """
912        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
914    def intersect(
915        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
916    ) -> Unionable:
917        """
918        Builds an INTERSECT expression.
919
920        Example:
921            >>> import sqlglot
922            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
923            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
924
925        Args:
926            expression: the SQL code string.
927                If an `Expression` instance is passed, it will be used as-is.
928            distinct: set the DISTINCT flag if and only if this is true.
929            dialect: the dialect used to parse the input expression.
930            opts: other options to use to parse the input expressions.
931
932        Returns:
933            The new Intersect expression.
934        """
935        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
937    def except_(
938        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
939    ) -> Unionable:
940        """
941        Builds an EXCEPT expression.
942
943        Example:
944            >>> import sqlglot
945            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
946            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
947
948        Args:
949            expression: the SQL code string.
950                If an `Expression` instance is passed, it will be used as-is.
951            distinct: set the DISTINCT flag if and only if this is true.
952            dialect: the dialect used to parse the input expression.
953            opts: other options to use to parse the input expressions.
954
955        Returns:
956            The new Except expression.
957        """
958        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
961class UDTF(DerivedTable, Unionable):
962    @property
963    def selects(self):
964        alias = self.args.get("alias")
965        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
968class Cache(Expression):
969    arg_types = {
970        "with": False,
971        "this": True,
972        "lazy": False,
973        "options": False,
974        "expression": False,
975    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
978class Uncache(Expression):
979    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
982class Create(Expression):
983    arg_types = {
984        "with": False,
985        "this": True,
986        "kind": True,
987        "expression": False,
988        "exists": False,
989        "properties": False,
990        "replace": False,
991        "unique": False,
992        "indexes": False,
993        "no_schema_binding": False,
994        "begin": False,
995        "clone": False,
996    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
1000class Clone(Expression):
1001    arg_types = {
1002        "this": True,
1003        "when": False,
1004        "kind": False,
1005        "expression": False,
1006    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1009class Describe(Expression):
1010    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1013class Pragma(Expression):
1014    pass
key = 'pragma'
class Set(Expression):
1017class Set(Expression):
1018    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1021class SetItem(Expression):
1022    arg_types = {
1023        "this": False,
1024        "expressions": False,
1025        "kind": False,
1026        "collate": False,  # MySQL SET NAMES statement
1027        "global": False,
1028    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1031class Show(Expression):
1032    arg_types = {
1033        "this": True,
1034        "target": False,
1035        "offset": False,
1036        "limit": False,
1037        "like": False,
1038        "where": False,
1039        "db": False,
1040        "full": False,
1041        "mutex": False,
1042        "query": False,
1043        "channel": False,
1044        "global": False,
1045        "log": False,
1046        "position": False,
1047        "types": False,
1048    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1051class UserDefinedFunction(Expression):
1052    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1055class CharacterSet(Expression):
1056    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1059class With(Expression):
1060    arg_types = {"expressions": True, "recursive": False}
1061
1062    @property
1063    def recursive(self) -> bool:
1064        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1067class WithinGroup(Expression):
1068    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1071class CTE(DerivedTable):
1072    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1075class TableAlias(Expression):
1076    arg_types = {"this": False, "columns": False}
1077
1078    @property
1079    def columns(self):
1080        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1083class BitString(Condition):
1084    pass
key = 'bitstring'
class HexString(Condition):
1087class HexString(Condition):
1088    pass
key = 'hexstring'
class ByteString(Condition):
1091class ByteString(Condition):
1092    pass
key = 'bytestring'
class RawString(Condition):
1095class RawString(Condition):
1096    pass
key = 'rawstring'
class Column(Condition):
1099class Column(Condition):
1100    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1101
1102    @property
1103    def table(self) -> str:
1104        return self.text("table")
1105
1106    @property
1107    def db(self) -> str:
1108        return self.text("db")
1109
1110    @property
1111    def catalog(self) -> str:
1112        return self.text("catalog")
1113
1114    @property
1115    def output_name(self) -> str:
1116        return self.name
1117
1118    @property
1119    def parts(self) -> t.List[Identifier]:
1120        """Return the parts of a column in order catalog, db, table, name."""
1121        return [
1122            t.cast(Identifier, self.args[part])
1123            for part in ("catalog", "db", "table", "this")
1124            if self.args.get(part)
1125        ]
1126
1127    def to_dot(self) -> Dot:
1128        """Converts the column into a dot expression."""
1129        parts = self.parts
1130        parent = self.parent
1131
1132        while parent:
1133            if isinstance(parent, Dot):
1134                parts.append(parent.expression)
1135            parent = parent.parent
1136
1137        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1127    def to_dot(self) -> Dot:
1128        """Converts the column into a dot expression."""
1129        parts = self.parts
1130        parent = self.parent
1131
1132        while parent:
1133            if isinstance(parent, Dot):
1134                parts.append(parent.expression)
1135            parent = parent.parent
1136
1137        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1140class ColumnPosition(Expression):
1141    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1144class ColumnDef(Expression):
1145    arg_types = {
1146        "this": True,
1147        "kind": False,
1148        "constraints": False,
1149        "exists": False,
1150        "position": False,
1151    }
1152
1153    @property
1154    def constraints(self) -> t.List[ColumnConstraint]:
1155        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1158class AlterColumn(Expression):
1159    arg_types = {
1160        "this": True,
1161        "dtype": False,
1162        "collate": False,
1163        "using": False,
1164        "default": False,
1165        "drop": False,
1166    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1169class RenameTable(Expression):
1170    pass
key = 'renametable'
class Comment(Expression):
1173class Comment(Expression):
1174    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1178class MergeTreeTTLAction(Expression):
1179    arg_types = {
1180        "this": True,
1181        "delete": False,
1182        "recompress": False,
1183        "to_disk": False,
1184        "to_volume": False,
1185    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1189class MergeTreeTTL(Expression):
1190    arg_types = {
1191        "expressions": True,
1192        "where": False,
1193        "group": False,
1194        "aggregates": False,
1195    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1198class ColumnConstraint(Expression):
1199    arg_types = {"this": False, "kind": True}
1200
1201    @property
1202    def kind(self) -> ColumnConstraintKind:
1203        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1206class ColumnConstraintKind(Expression):
1207    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1210class AutoIncrementColumnConstraint(ColumnConstraintKind):
1211    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1214class CaseSpecificColumnConstraint(ColumnConstraintKind):
1215    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1218class CharacterSetColumnConstraint(ColumnConstraintKind):
1219    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1222class CheckColumnConstraint(ColumnConstraintKind):
1223    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1226class CollateColumnConstraint(ColumnConstraintKind):
1227    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1230class CommentColumnConstraint(ColumnConstraintKind):
1231    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1234class CompressColumnConstraint(ColumnConstraintKind):
1235    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1238class DateFormatColumnConstraint(ColumnConstraintKind):
1239    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1242class DefaultColumnConstraint(ColumnConstraintKind):
1243    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1246class EncodeColumnConstraint(ColumnConstraintKind):
1247    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1250class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1251    # this: True -> ALWAYS, this: False -> BY DEFAULT
1252    arg_types = {
1253        "this": False,
1254        "expression": False,
1255        "on_null": False,
1256        "start": False,
1257        "increment": False,
1258        "minvalue": False,
1259        "maxvalue": False,
1260        "cycle": False,
1261    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1264class InlineLengthColumnConstraint(ColumnConstraintKind):
1265    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1268class NotNullColumnConstraint(ColumnConstraintKind):
1269    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1273class OnUpdateColumnConstraint(ColumnConstraintKind):
1274    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1277class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1278    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1281class TitleColumnConstraint(ColumnConstraintKind):
1282    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1285class UniqueColumnConstraint(ColumnConstraintKind):
1286    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1289class UppercaseColumnConstraint(ColumnConstraintKind):
1290    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1293class PathColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1297class Constraint(Expression):
1298    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1301class Delete(Expression):
1302    arg_types = {
1303        "with": False,
1304        "this": False,
1305        "using": False,
1306        "where": False,
1307        "returning": False,
1308        "limit": False,
1309        "tables": False,  # Multiple-Table Syntax (MySQL)
1310    }
1311
1312    def delete(
1313        self,
1314        table: ExpOrStr,
1315        dialect: DialectType = None,
1316        copy: bool = True,
1317        **opts,
1318    ) -> Delete:
1319        """
1320        Create a DELETE expression or replace the table on an existing DELETE expression.
1321
1322        Example:
1323            >>> delete("tbl").sql()
1324            'DELETE FROM tbl'
1325
1326        Args:
1327            table: the table from which to delete.
1328            dialect: the dialect used to parse the input expression.
1329            copy: if `False`, modify this expression instance in-place.
1330            opts: other options to use to parse the input expressions.
1331
1332        Returns:
1333            Delete: the modified expression.
1334        """
1335        return _apply_builder(
1336            expression=table,
1337            instance=self,
1338            arg="this",
1339            dialect=dialect,
1340            into=Table,
1341            copy=copy,
1342            **opts,
1343        )
1344
1345    def where(
1346        self,
1347        *expressions: t.Optional[ExpOrStr],
1348        append: bool = True,
1349        dialect: DialectType = None,
1350        copy: bool = True,
1351        **opts,
1352    ) -> Delete:
1353        """
1354        Append to or set the WHERE expressions.
1355
1356        Example:
1357            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1358            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1359
1360        Args:
1361            *expressions: the SQL code strings to parse.
1362                If an `Expression` instance is passed, it will be used as-is.
1363                Multiple expressions are combined with an AND operator.
1364            append: if `True`, AND the new expressions to any existing expression.
1365                Otherwise, this resets the expression.
1366            dialect: the dialect used to parse the input expressions.
1367            copy: if `False`, modify this expression instance in-place.
1368            opts: other options to use to parse the input expressions.
1369
1370        Returns:
1371            Delete: the modified expression.
1372        """
1373        return _apply_conjunction_builder(
1374            *expressions,
1375            instance=self,
1376            arg="where",
1377            append=append,
1378            into=Where,
1379            dialect=dialect,
1380            copy=copy,
1381            **opts,
1382        )
1383
1384    def returning(
1385        self,
1386        expression: ExpOrStr,
1387        dialect: DialectType = None,
1388        copy: bool = True,
1389        **opts,
1390    ) -> Delete:
1391        """
1392        Set the RETURNING expression. Not supported by all dialects.
1393
1394        Example:
1395            >>> delete("tbl").returning("*", dialect="postgres").sql()
1396            'DELETE FROM tbl RETURNING *'
1397
1398        Args:
1399            expression: the SQL code strings to parse.
1400                If an `Expression` instance is passed, it will be used as-is.
1401            dialect: the dialect used to parse the input expressions.
1402            copy: if `False`, modify this expression instance in-place.
1403            opts: other options to use to parse the input expressions.
1404
1405        Returns:
1406            Delete: the modified expression.
1407        """
1408        return _apply_builder(
1409            expression=expression,
1410            instance=self,
1411            arg="returning",
1412            prefix="RETURNING",
1413            dialect=dialect,
1414            copy=copy,
1415            into=Returning,
1416            **opts,
1417        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False, 'tables': False}
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1312    def delete(
1313        self,
1314        table: ExpOrStr,
1315        dialect: DialectType = None,
1316        copy: bool = True,
1317        **opts,
1318    ) -> Delete:
1319        """
1320        Create a DELETE expression or replace the table on an existing DELETE expression.
1321
1322        Example:
1323            >>> delete("tbl").sql()
1324            'DELETE FROM tbl'
1325
1326        Args:
1327            table: the table from which to delete.
1328            dialect: the dialect used to parse the input expression.
1329            copy: if `False`, modify this expression instance in-place.
1330            opts: other options to use to parse the input expressions.
1331
1332        Returns:
1333            Delete: the modified expression.
1334        """
1335        return _apply_builder(
1336            expression=table,
1337            instance=self,
1338            arg="this",
1339            dialect=dialect,
1340            into=Table,
1341            copy=copy,
1342            **opts,
1343        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1345    def where(
1346        self,
1347        *expressions: t.Optional[ExpOrStr],
1348        append: bool = True,
1349        dialect: DialectType = None,
1350        copy: bool = True,
1351        **opts,
1352    ) -> Delete:
1353        """
1354        Append to or set the WHERE expressions.
1355
1356        Example:
1357            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1358            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1359
1360        Args:
1361            *expressions: the SQL code strings to parse.
1362                If an `Expression` instance is passed, it will be used as-is.
1363                Multiple expressions are combined with an AND operator.
1364            append: if `True`, AND the new expressions to any existing expression.
1365                Otherwise, this resets the expression.
1366            dialect: the dialect used to parse the input expressions.
1367            copy: if `False`, modify this expression instance in-place.
1368            opts: other options to use to parse the input expressions.
1369
1370        Returns:
1371            Delete: the modified expression.
1372        """
1373        return _apply_conjunction_builder(
1374            *expressions,
1375            instance=self,
1376            arg="where",
1377            append=append,
1378            into=Where,
1379            dialect=dialect,
1380            copy=copy,
1381            **opts,
1382        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1384    def returning(
1385        self,
1386        expression: ExpOrStr,
1387        dialect: DialectType = None,
1388        copy: bool = True,
1389        **opts,
1390    ) -> Delete:
1391        """
1392        Set the RETURNING expression. Not supported by all dialects.
1393
1394        Example:
1395            >>> delete("tbl").returning("*", dialect="postgres").sql()
1396            'DELETE FROM tbl RETURNING *'
1397
1398        Args:
1399            expression: the SQL code strings to parse.
1400                If an `Expression` instance is passed, it will be used as-is.
1401            dialect: the dialect used to parse the input expressions.
1402            copy: if `False`, modify this expression instance in-place.
1403            opts: other options to use to parse the input expressions.
1404
1405        Returns:
1406            Delete: the modified expression.
1407        """
1408        return _apply_builder(
1409            expression=expression,
1410            instance=self,
1411            arg="returning",
1412            prefix="RETURNING",
1413            dialect=dialect,
1414            copy=copy,
1415            into=Returning,
1416            **opts,
1417        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1420class Drop(Expression):
1421    arg_types = {
1422        "this": False,
1423        "kind": False,
1424        "exists": False,
1425        "temporary": False,
1426        "materialized": False,
1427        "cascade": False,
1428        "constraints": False,
1429        "purge": False,
1430    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1433class Filter(Expression):
1434    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1437class Check(Expression):
1438    pass
key = 'check'
class Directory(Expression):
1441class Directory(Expression):
1442    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1443    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1446class ForeignKey(Expression):
1447    arg_types = {
1448        "expressions": True,
1449        "reference": False,
1450        "delete": False,
1451        "update": False,
1452    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1455class PrimaryKey(Expression):
1456    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1461class Into(Expression):
1462    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1465class From(Expression):
1466    @property
1467    def name(self) -> str:
1468        return self.this.name
1469
1470    @property
1471    def alias_or_name(self) -> str:
1472        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1475class Having(Expression):
1476    pass
key = 'having'
class Hint(Expression):
1479class Hint(Expression):
1480    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1483class JoinHint(Expression):
1484    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1487class Identifier(Expression):
1488    arg_types = {"this": True, "quoted": False}
1489
1490    @property
1491    def quoted(self) -> bool:
1492        return bool(self.args.get("quoted"))
1493
1494    @property
1495    def hashable_args(self) -> t.Any:
1496        return (self.this, self.quoted)
1497
1498    @property
1499    def output_name(self) -> str:
1500        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1503class Index(Expression):
1504    arg_types = {
1505        "this": False,
1506        "table": False,
1507        "using": False,
1508        "where": False,
1509        "columns": False,
1510        "unique": False,
1511        "primary": False,
1512        "amp": False,  # teradata
1513        "partition_by": False,  # teradata
1514    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(Expression):
1517class Insert(Expression):
1518    arg_types = {
1519        "with": False,
1520        "this": True,
1521        "expression": False,
1522        "conflict": False,
1523        "returning": False,
1524        "overwrite": False,
1525        "exists": False,
1526        "partition": False,
1527        "alternative": False,
1528        "where": False,
1529        "ignore": False,
1530    }
1531
1532    def with_(
1533        self,
1534        alias: ExpOrStr,
1535        as_: ExpOrStr,
1536        recursive: t.Optional[bool] = None,
1537        append: bool = True,
1538        dialect: DialectType = None,
1539        copy: bool = True,
1540        **opts,
1541    ) -> Insert:
1542        """
1543        Append to or set the common table expressions.
1544
1545        Example:
1546            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1547            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1548
1549        Args:
1550            alias: the SQL code string to parse as the table name.
1551                If an `Expression` instance is passed, this is used as-is.
1552            as_: the SQL code string to parse as the table expression.
1553                If an `Expression` instance is passed, it will be used as-is.
1554            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1555            append: if `True`, add to any existing expressions.
1556                Otherwise, this resets the expressions.
1557            dialect: the dialect used to parse the input expression.
1558            copy: if `False`, modify this expression instance in-place.
1559            opts: other options to use to parse the input expressions.
1560
1561        Returns:
1562            The modified expression.
1563        """
1564        return _apply_cte_builder(
1565            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1566        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1532    def with_(
1533        self,
1534        alias: ExpOrStr,
1535        as_: ExpOrStr,
1536        recursive: t.Optional[bool] = None,
1537        append: bool = True,
1538        dialect: DialectType = None,
1539        copy: bool = True,
1540        **opts,
1541    ) -> Insert:
1542        """
1543        Append to or set the common table expressions.
1544
1545        Example:
1546            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1547            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1548
1549        Args:
1550            alias: the SQL code string to parse as the table name.
1551                If an `Expression` instance is passed, this is used as-is.
1552            as_: the SQL code string to parse as the table expression.
1553                If an `Expression` instance is passed, it will be used as-is.
1554            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1555            append: if `True`, add to any existing expressions.
1556                Otherwise, this resets the expressions.
1557            dialect: the dialect used to parse the input expression.
1558            copy: if `False`, modify this expression instance in-place.
1559            opts: other options to use to parse the input expressions.
1560
1561        Returns:
1562            The modified expression.
1563        """
1564        return _apply_cte_builder(
1565            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1566        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1569class OnConflict(Expression):
1570    arg_types = {
1571        "duplicate": False,
1572        "expressions": False,
1573        "nothing": False,
1574        "key": False,
1575        "constraint": False,
1576    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1579class Returning(Expression):
1580    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1584class Introducer(Expression):
1585    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1589class National(Expression):
1590    pass
key = 'national'
class LoadData(Expression):
1593class LoadData(Expression):
1594    arg_types = {
1595        "this": True,
1596        "local": False,
1597        "overwrite": False,
1598        "inpath": True,
1599        "partition": False,
1600        "input_format": False,
1601        "serde": False,
1602    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1605class Partition(Expression):
1606    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1609class Fetch(Expression):
1610    arg_types = {
1611        "direction": False,
1612        "count": False,
1613        "percent": False,
1614        "with_ties": False,
1615    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1618class Group(Expression):
1619    arg_types = {
1620        "expressions": False,
1621        "grouping_sets": False,
1622        "cube": False,
1623        "rollup": False,
1624        "totals": False,
1625        "all": False,
1626    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1629class Lambda(Expression):
1630    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1633class Limit(Expression):
1634    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1637class Literal(Condition):
1638    arg_types = {"this": True, "is_string": True}
1639
1640    @property
1641    def hashable_args(self) -> t.Any:
1642        return (self.this, self.args.get("is_string"))
1643
1644    @classmethod
1645    def number(cls, number) -> Literal:
1646        return cls(this=str(number), is_string=False)
1647
1648    @classmethod
1649    def string(cls, string) -> Literal:
1650        return cls(this=str(string), is_string=True)
1651
1652    @property
1653    def output_name(self) -> str:
1654        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1644    @classmethod
1645    def number(cls, number) -> Literal:
1646        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1648    @classmethod
1649    def string(cls, string) -> Literal:
1650        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1657class Join(Expression):
1658    arg_types = {
1659        "this": True,
1660        "on": False,
1661        "side": False,
1662        "kind": False,
1663        "using": False,
1664        "method": False,
1665        "global": False,
1666        "hint": False,
1667    }
1668
1669    @property
1670    def method(self) -> str:
1671        return self.text("method").upper()
1672
1673    @property
1674    def kind(self) -> str:
1675        return self.text("kind").upper()
1676
1677    @property
1678    def side(self) -> str:
1679        return self.text("side").upper()
1680
1681    @property
1682    def hint(self) -> str:
1683        return self.text("hint").upper()
1684
1685    @property
1686    def alias_or_name(self) -> str:
1687        return self.this.alias_or_name
1688
1689    def on(
1690        self,
1691        *expressions: t.Optional[ExpOrStr],
1692        append: bool = True,
1693        dialect: DialectType = None,
1694        copy: bool = True,
1695        **opts,
1696    ) -> Join:
1697        """
1698        Append to or set the ON expressions.
1699
1700        Example:
1701            >>> import sqlglot
1702            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1703            'JOIN x ON y = 1'
1704
1705        Args:
1706            *expressions: the SQL code strings to parse.
1707                If an `Expression` instance is passed, it will be used as-is.
1708                Multiple expressions are combined with an AND operator.
1709            append: if `True`, AND the new expressions to any existing expression.
1710                Otherwise, this resets the expression.
1711            dialect: the dialect used to parse the input expressions.
1712            copy: if `False`, modify this expression instance in-place.
1713            opts: other options to use to parse the input expressions.
1714
1715        Returns:
1716            The modified Join expression.
1717        """
1718        join = _apply_conjunction_builder(
1719            *expressions,
1720            instance=self,
1721            arg="on",
1722            append=append,
1723            dialect=dialect,
1724            copy=copy,
1725            **opts,
1726        )
1727
1728        if join.kind == "CROSS":
1729            join.set("kind", None)
1730
1731        return join
1732
1733    def using(
1734        self,
1735        *expressions: t.Optional[ExpOrStr],
1736        append: bool = True,
1737        dialect: DialectType = None,
1738        copy: bool = True,
1739        **opts,
1740    ) -> Join:
1741        """
1742        Append to or set the USING expressions.
1743
1744        Example:
1745            >>> import sqlglot
1746            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1747            'JOIN x USING (foo, bla)'
1748
1749        Args:
1750            *expressions: the SQL code strings to parse.
1751                If an `Expression` instance is passed, it will be used as-is.
1752            append: if `True`, concatenate the new expressions to the existing "using" list.
1753                Otherwise, this resets the expression.
1754            dialect: the dialect used to parse the input expressions.
1755            copy: if `False`, modify this expression instance in-place.
1756            opts: other options to use to parse the input expressions.
1757
1758        Returns:
1759            The modified Join expression.
1760        """
1761        join = _apply_list_builder(
1762            *expressions,
1763            instance=self,
1764            arg="using",
1765            append=append,
1766            dialect=dialect,
1767            copy=copy,
1768            **opts,
1769        )
1770
1771        if join.kind == "CROSS":
1772            join.set("kind", None)
1773
1774        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1689    def on(
1690        self,
1691        *expressions: t.Optional[ExpOrStr],
1692        append: bool = True,
1693        dialect: DialectType = None,
1694        copy: bool = True,
1695        **opts,
1696    ) -> Join:
1697        """
1698        Append to or set the ON expressions.
1699
1700        Example:
1701            >>> import sqlglot
1702            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1703            'JOIN x ON y = 1'
1704
1705        Args:
1706            *expressions: the SQL code strings to parse.
1707                If an `Expression` instance is passed, it will be used as-is.
1708                Multiple expressions are combined with an AND operator.
1709            append: if `True`, AND the new expressions to any existing expression.
1710                Otherwise, this resets the expression.
1711            dialect: the dialect used to parse the input expressions.
1712            copy: if `False`, modify this expression instance in-place.
1713            opts: other options to use to parse the input expressions.
1714
1715        Returns:
1716            The modified Join expression.
1717        """
1718        join = _apply_conjunction_builder(
1719            *expressions,
1720            instance=self,
1721            arg="on",
1722            append=append,
1723            dialect=dialect,
1724            copy=copy,
1725            **opts,
1726        )
1727
1728        if join.kind == "CROSS":
1729            join.set("kind", None)
1730
1731        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1733    def using(
1734        self,
1735        *expressions: t.Optional[ExpOrStr],
1736        append: bool = True,
1737        dialect: DialectType = None,
1738        copy: bool = True,
1739        **opts,
1740    ) -> Join:
1741        """
1742        Append to or set the USING expressions.
1743
1744        Example:
1745            >>> import sqlglot
1746            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1747            'JOIN x USING (foo, bla)'
1748
1749        Args:
1750            *expressions: the SQL code strings to parse.
1751                If an `Expression` instance is passed, it will be used as-is.
1752            append: if `True`, concatenate the new expressions to the existing "using" list.
1753                Otherwise, this resets the expression.
1754            dialect: the dialect used to parse the input expressions.
1755            copy: if `False`, modify this expression instance in-place.
1756            opts: other options to use to parse the input expressions.
1757
1758        Returns:
1759            The modified Join expression.
1760        """
1761        join = _apply_list_builder(
1762            *expressions,
1763            instance=self,
1764            arg="using",
1765            append=append,
1766            dialect=dialect,
1767            copy=copy,
1768            **opts,
1769        )
1770
1771        if join.kind == "CROSS":
1772            join.set("kind", None)
1773
1774        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1777class Lateral(UDTF):
1778    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1781class MatchRecognize(Expression):
1782    arg_types = {
1783        "partition_by": False,
1784        "order": False,
1785        "measures": False,
1786        "rows": False,
1787        "after": False,
1788        "pattern": False,
1789        "define": False,
1790        "alias": False,
1791    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1796class Final(Expression):
1797    pass
key = 'final'
class Offset(Expression):
1800class Offset(Expression):
1801    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1804class Order(Expression):
1805    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1810class Cluster(Order):
1811    pass
key = 'cluster'
class Distribute(Order):
1814class Distribute(Order):
1815    pass
key = 'distribute'
class Sort(Order):
1818class Sort(Order):
1819    pass
key = 'sort'
class Ordered(Expression):
1822class Ordered(Expression):
1823    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1826class Property(Expression):
1827    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1830class AlgorithmProperty(Property):
1831    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1834class AutoIncrementProperty(Property):
1835    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1838class BlockCompressionProperty(Property):
1839    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1842class CharacterSetProperty(Property):
1843    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1846class ChecksumProperty(Property):
1847    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1850class CollateProperty(Property):
1851    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1854class CopyGrantsProperty(Property):
1855    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1858class DataBlocksizeProperty(Property):
1859    arg_types = {
1860        "size": False,
1861        "units": False,
1862        "minimum": False,
1863        "maximum": False,
1864        "default": False,
1865    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1868class DefinerProperty(Property):
1869    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1872class DistKeyProperty(Property):
1873    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1876class DistStyleProperty(Property):
1877    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1880class EngineProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1884class ToTableProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1888class ExecuteAsProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1892class ExternalProperty(Property):
1893    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1896class FallbackProperty(Property):
1897    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1900class FileFormatProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1904class FreespaceProperty(Property):
1905    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1908class InputOutputFormat(Expression):
1909    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1912class IsolatedLoadingProperty(Property):
1913    arg_types = {
1914        "no": True,
1915        "concurrent": True,
1916        "for_all": True,
1917        "for_insert": True,
1918        "for_none": True,
1919    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1922class JournalProperty(Property):
1923    arg_types = {
1924        "no": False,
1925        "dual": False,
1926        "before": False,
1927        "local": False,
1928        "after": False,
1929    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1932class LanguageProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1937class ClusteredByProperty(Property):
1938    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1941class DictProperty(Property):
1942    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1945class DictSubProperty(Property):
1946    pass
key = 'dictsubproperty'
class DictRange(Property):
1949class DictRange(Property):
1950    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1955class OnCluster(Property):
1956    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1959class LikeProperty(Property):
1960    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1963class LocationProperty(Property):
1964    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1967class LockingProperty(Property):
1968    arg_types = {
1969        "this": False,
1970        "kind": True,
1971        "for_or_in": True,
1972        "lock_type": True,
1973        "override": False,
1974    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1977class LogProperty(Property):
1978    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1981class MaterializedProperty(Property):
1982    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1985class MergeBlockRatioProperty(Property):
1986    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
1989class NoPrimaryIndexProperty(Property):
1990    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1993class OnCommitProperty(Property):
1994    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1997class PartitionedByProperty(Property):
1998    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2001class ReturnsProperty(Property):
2002    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2005class RowFormatProperty(Property):
2006    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2009class RowFormatDelimitedProperty(Property):
2010    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2011    arg_types = {
2012        "fields": False,
2013        "escaped": False,
2014        "collection_items": False,
2015        "map_keys": False,
2016        "lines": False,
2017        "null": False,
2018        "serde": False,
2019    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2022class RowFormatSerdeProperty(Property):
2023    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2026class SchemaCommentProperty(Property):
2027    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2030class SerdeProperties(Property):
2031    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2034class SetProperty(Property):
2035    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2038class SettingsProperty(Property):
2039    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2042class SortKeyProperty(Property):
2043    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2046class SqlSecurityProperty(Property):
2047    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2050class StabilityProperty(Property):
2051    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2054class TemporaryProperty(Property):
2055    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2058class TransientProperty(Property):
2059    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2062class VolatileProperty(Property):
2063    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2066class WithDataProperty(Property):
2067    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2070class WithJournalTableProperty(Property):
2071    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2074class Properties(Expression):
2075    arg_types = {"expressions": True}
2076
2077    NAME_TO_PROPERTY = {
2078        "ALGORITHM": AlgorithmProperty,
2079        "AUTO_INCREMENT": AutoIncrementProperty,
2080        "CHARACTER SET": CharacterSetProperty,
2081        "CLUSTERED_BY": ClusteredByProperty,
2082        "COLLATE": CollateProperty,
2083        "COMMENT": SchemaCommentProperty,
2084        "DEFINER": DefinerProperty,
2085        "DISTKEY": DistKeyProperty,
2086        "DISTSTYLE": DistStyleProperty,
2087        "ENGINE": EngineProperty,
2088        "EXECUTE AS": ExecuteAsProperty,
2089        "FORMAT": FileFormatProperty,
2090        "LANGUAGE": LanguageProperty,
2091        "LOCATION": LocationProperty,
2092        "PARTITIONED_BY": PartitionedByProperty,
2093        "RETURNS": ReturnsProperty,
2094        "ROW_FORMAT": RowFormatProperty,
2095        "SORTKEY": SortKeyProperty,
2096    }
2097
2098    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2099
2100    # CREATE property locations
2101    # Form: schema specified
2102    #   create [POST_CREATE]
2103    #     table a [POST_NAME]
2104    #     (b int) [POST_SCHEMA]
2105    #     with ([POST_WITH])
2106    #     index (b) [POST_INDEX]
2107    #
2108    # Form: alias selection
2109    #   create [POST_CREATE]
2110    #     table a [POST_NAME]
2111    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2112    #     index (c) [POST_INDEX]
2113    class Location(AutoName):
2114        POST_CREATE = auto()
2115        POST_NAME = auto()
2116        POST_SCHEMA = auto()
2117        POST_WITH = auto()
2118        POST_ALIAS = auto()
2119        POST_EXPRESSION = auto()
2120        POST_INDEX = auto()
2121        UNSUPPORTED = auto()
2122
2123    @classmethod
2124    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2125        expressions = []
2126        for key, value in properties_dict.items():
2127            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2128            if property_cls:
2129                expressions.append(property_cls(this=convert(value)))
2130            else:
2131                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2132
2133        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2123    @classmethod
2124    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2125        expressions = []
2126        for key, value in properties_dict.items():
2127            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2128            if property_cls:
2129                expressions.append(property_cls(this=convert(value)))
2130            else:
2131                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2132
2133        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2113    class Location(AutoName):
2114        POST_CREATE = auto()
2115        POST_NAME = auto()
2116        POST_SCHEMA = auto()
2117        POST_WITH = auto()
2118        POST_ALIAS = auto()
2119        POST_EXPRESSION = auto()
2120        POST_INDEX = auto()
2121        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2136class Qualify(Expression):
2137    pass
key = 'qualify'
class Return(Expression):
2141class Return(Expression):
2142    pass
key = 'return'
class Reference(Expression):
2145class Reference(Expression):
2146    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2149class Tuple(Expression):
2150    arg_types = {"expressions": False}
2151
2152    def isin(
2153        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2154    ) -> In:
2155        return In(
2156            this=_maybe_copy(self, copy),
2157            expressions=[convert(e, copy=copy) for e in expressions],
2158            query=maybe_parse(query, copy=copy, **opts) if query else None,
2159        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2152    def isin(
2153        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2154    ) -> In:
2155        return In(
2156            this=_maybe_copy(self, copy),
2157            expressions=[convert(e, copy=copy) for e in expressions],
2158            query=maybe_parse(query, copy=copy, **opts) if query else None,
2159        )
key = 'tuple'
class Subqueryable(Unionable):
2162class Subqueryable(Unionable):
2163    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2164        """
2165        Convert this expression to an aliased expression that can be used as a Subquery.
2166
2167        Example:
2168            >>> subquery = Select().select("x").from_("tbl").subquery()
2169            >>> Select().select("x").from_(subquery).sql()
2170            'SELECT x FROM (SELECT x FROM tbl)'
2171
2172        Args:
2173            alias (str | Identifier): an optional alias for the subquery
2174            copy (bool): if `False`, modify this expression instance in-place.
2175
2176        Returns:
2177            Alias: the subquery
2178        """
2179        instance = _maybe_copy(self, copy)
2180        if not isinstance(alias, Expression):
2181            alias = TableAlias(this=to_identifier(alias)) if alias else None
2182
2183        return Subquery(this=instance, alias=alias)
2184
2185    def limit(
2186        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2187    ) -> Select:
2188        raise NotImplementedError
2189
2190    @property
2191    def ctes(self):
2192        with_ = self.args.get("with")
2193        if not with_:
2194            return []
2195        return with_.expressions
2196
2197    @property
2198    def selects(self):
2199        raise NotImplementedError("Subqueryable objects must implement `selects`")
2200
2201    @property
2202    def named_selects(self):
2203        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2204
2205    def with_(
2206        self,
2207        alias: ExpOrStr,
2208        as_: ExpOrStr,
2209        recursive: t.Optional[bool] = None,
2210        append: bool = True,
2211        dialect: DialectType = None,
2212        copy: bool = True,
2213        **opts,
2214    ) -> Subqueryable:
2215        """
2216        Append to or set the common table expressions.
2217
2218        Example:
2219            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2220            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2221
2222        Args:
2223            alias: the SQL code string to parse as the table name.
2224                If an `Expression` instance is passed, this is used as-is.
2225            as_: the SQL code string to parse as the table expression.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2228            append: if `True`, add to any existing expressions.
2229                Otherwise, this resets the expressions.
2230            dialect: the dialect used to parse the input expression.
2231            copy: if `False`, modify this expression instance in-place.
2232            opts: other options to use to parse the input expressions.
2233
2234        Returns:
2235            The modified expression.
2236        """
2237        return _apply_cte_builder(
2238            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2239        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2163    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2164        """
2165        Convert this expression to an aliased expression that can be used as a Subquery.
2166
2167        Example:
2168            >>> subquery = Select().select("x").from_("tbl").subquery()
2169            >>> Select().select("x").from_(subquery).sql()
2170            'SELECT x FROM (SELECT x FROM tbl)'
2171
2172        Args:
2173            alias (str | Identifier): an optional alias for the subquery
2174            copy (bool): if `False`, modify this expression instance in-place.
2175
2176        Returns:
2177            Alias: the subquery
2178        """
2179        instance = _maybe_copy(self, copy)
2180        if not isinstance(alias, Expression):
2181            alias = TableAlias(this=to_identifier(alias)) if alias else None
2182
2183        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2185    def limit(
2186        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2187    ) -> Select:
2188        raise NotImplementedError
ctes
selects
named_selects
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2205    def with_(
2206        self,
2207        alias: ExpOrStr,
2208        as_: ExpOrStr,
2209        recursive: t.Optional[bool] = None,
2210        append: bool = True,
2211        dialect: DialectType = None,
2212        copy: bool = True,
2213        **opts,
2214    ) -> Subqueryable:
2215        """
2216        Append to or set the common table expressions.
2217
2218        Example:
2219            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2220            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2221
2222        Args:
2223            alias: the SQL code string to parse as the table name.
2224                If an `Expression` instance is passed, this is used as-is.
2225            as_: the SQL code string to parse as the table expression.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2228            append: if `True`, add to any existing expressions.
2229                Otherwise, this resets the expressions.
2230            dialect: the dialect used to parse the input expression.
2231            copy: if `False`, modify this expression instance in-place.
2232            opts: other options to use to parse the input expressions.
2233
2234        Returns:
2235            The modified expression.
2236        """
2237        return _apply_cte_builder(
2238            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2239        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2266class WithTableHint(Expression):
2267    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2271class IndexTableHint(Expression):
2272    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2275class Table(Expression):
2276    arg_types = {
2277        "this": True,
2278        "alias": False,
2279        "db": False,
2280        "catalog": False,
2281        "laterals": False,
2282        "joins": False,
2283        "pivots": False,
2284        "hints": False,
2285        "system_time": False,
2286        "wrapped": False,
2287    }
2288
2289    @property
2290    def name(self) -> str:
2291        if isinstance(self.this, Func):
2292            return ""
2293        return self.this.name
2294
2295    @property
2296    def db(self) -> str:
2297        return self.text("db")
2298
2299    @property
2300    def catalog(self) -> str:
2301        return self.text("catalog")
2302
2303    @property
2304    def parts(self) -> t.List[Identifier]:
2305        """Return the parts of a table in order catalog, db, table."""
2306        return [
2307            t.cast(Identifier, self.args[part])
2308            for part in ("catalog", "db", "this")
2309            if self.args.get(part)
2310        ]
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'wrapped': False}
name: str
db: str
catalog: str

Return the parts of a table in order catalog, db, table.

key = 'table'
class SystemTime(Expression):
2314class SystemTime(Expression):
2315    arg_types = {
2316        "this": False,
2317        "expression": False,
2318        "kind": True,
2319    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2322class Union(Subqueryable):
2323    arg_types = {
2324        "with": False,
2325        "this": True,
2326        "expression": True,
2327        "distinct": False,
2328        **QUERY_MODIFIERS,
2329    }
2330
2331    def limit(
2332        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2333    ) -> Select:
2334        """
2335        Set the LIMIT expression.
2336
2337        Example:
2338            >>> select("1").union(select("1")).limit(1).sql()
2339            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2340
2341        Args:
2342            expression: the SQL code string to parse.
2343                This can also be an integer.
2344                If a `Limit` instance is passed, this is used as-is.
2345                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2346            dialect: the dialect used to parse the input expression.
2347            copy: if `False`, modify this expression instance in-place.
2348            opts: other options to use to parse the input expressions.
2349
2350        Returns:
2351            The limited subqueryable.
2352        """
2353        return (
2354            select("*")
2355            .from_(self.subquery(alias="_l_0", copy=copy))
2356            .limit(expression, dialect=dialect, copy=False, **opts)
2357        )
2358
2359    def select(
2360        self,
2361        *expressions: t.Optional[ExpOrStr],
2362        append: bool = True,
2363        dialect: DialectType = None,
2364        copy: bool = True,
2365        **opts,
2366    ) -> Union:
2367        """Append to or set the SELECT of the union recursively.
2368
2369        Example:
2370            >>> from sqlglot import parse_one
2371            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2372            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2373
2374        Args:
2375            *expressions: the SQL code strings to parse.
2376                If an `Expression` instance is passed, it will be used as-is.
2377            append: if `True`, add to any existing expressions.
2378                Otherwise, this resets the expressions.
2379            dialect: the dialect used to parse the input expressions.
2380            copy: if `False`, modify this expression instance in-place.
2381            opts: other options to use to parse the input expressions.
2382
2383        Returns:
2384            Union: the modified expression.
2385        """
2386        this = self.copy() if copy else self
2387        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2388        this.expression.unnest().select(
2389            *expressions, append=append, dialect=dialect, copy=False, **opts
2390        )
2391        return this
2392
2393    @property
2394    def named_selects(self):
2395        return self.this.unnest().named_selects
2396
2397    @property
2398    def is_star(self) -> bool:
2399        return self.this.is_star or self.expression.is_star
2400
2401    @property
2402    def selects(self):
2403        return self.this.unnest().selects
2404
2405    @property
2406    def left(self):
2407        return self.this
2408
2409    @property
2410    def right(self):
2411        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2331    def limit(
2332        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2333    ) -> Select:
2334        """
2335        Set the LIMIT expression.
2336
2337        Example:
2338            >>> select("1").union(select("1")).limit(1).sql()
2339            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2340
2341        Args:
2342            expression: the SQL code string to parse.
2343                This can also be an integer.
2344                If a `Limit` instance is passed, this is used as-is.
2345                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2346            dialect: the dialect used to parse the input expression.
2347            copy: if `False`, modify this expression instance in-place.
2348            opts: other options to use to parse the input expressions.
2349
2350        Returns:
2351            The limited subqueryable.
2352        """
2353        return (
2354            select("*")
2355            .from_(self.subquery(alias="_l_0", copy=copy))
2356            .limit(expression, dialect=dialect, copy=False, **opts)
2357        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2359    def select(
2360        self,
2361        *expressions: t.Optional[ExpOrStr],
2362        append: bool = True,
2363        dialect: DialectType = None,
2364        copy: bool = True,
2365        **opts,
2366    ) -> Union:
2367        """Append to or set the SELECT of the union recursively.
2368
2369        Example:
2370            >>> from sqlglot import parse_one
2371            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2372            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2373
2374        Args:
2375            *expressions: the SQL code strings to parse.
2376                If an `Expression` instance is passed, it will be used as-is.
2377            append: if `True`, add to any existing expressions.
2378                Otherwise, this resets the expressions.
2379            dialect: the dialect used to parse the input expressions.
2380            copy: if `False`, modify this expression instance in-place.
2381            opts: other options to use to parse the input expressions.
2382
2383        Returns:
2384            Union: the modified expression.
2385        """
2386        this = self.copy() if copy else self
2387        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2388        this.expression.unnest().select(
2389            *expressions, append=append, dialect=dialect, copy=False, **opts
2390        )
2391        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects
is_star: bool

Checks whether an expression is a star.

selects
left
right
key = 'union'
class Except(Union):
2414class Except(Union):
2415    pass
key = 'except'
class Intersect(Union):
2418class Intersect(Union):
2419    pass
key = 'intersect'
class Unnest(UDTF):
2422class Unnest(UDTF):
2423    arg_types = {
2424        "expressions": True,
2425        "ordinality": False,
2426        "alias": False,
2427        "offset": False,
2428    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2431class Update(Expression):
2432    arg_types = {
2433        "with": False,
2434        "this": False,
2435        "expressions": True,
2436        "from": False,
2437        "where": False,
2438        "returning": False,
2439        "limit": False,
2440    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2443class Values(UDTF):
2444    arg_types = {
2445        "expressions": True,
2446        "ordinality": False,
2447        "alias": False,
2448    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2451class Var(Expression):
2452    pass
key = 'var'
class Schema(Expression):
2455class Schema(Expression):
2456    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2461class Lock(Expression):
2462    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2465class Select(Subqueryable):
2466    arg_types = {
2467        "with": False,
2468        "kind": False,
2469        "expressions": False,
2470        "hint": False,
2471        "distinct": False,
2472        "into": False,
2473        "from": False,
2474        **QUERY_MODIFIERS,
2475    }
2476
2477    def from_(
2478        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2479    ) -> Select:
2480        """
2481        Set the FROM expression.
2482
2483        Example:
2484            >>> Select().from_("tbl").select("x").sql()
2485            'SELECT x FROM tbl'
2486
2487        Args:
2488            expression : the SQL code strings to parse.
2489                If a `From` instance is passed, this is used as-is.
2490                If another `Expression` instance is passed, it will be wrapped in a `From`.
2491            dialect: the dialect used to parse the input expression.
2492            copy: if `False`, modify this expression instance in-place.
2493            opts: other options to use to parse the input expressions.
2494
2495        Returns:
2496            The modified Select expression.
2497        """
2498        return _apply_builder(
2499            expression=expression,
2500            instance=self,
2501            arg="from",
2502            into=From,
2503            prefix="FROM",
2504            dialect=dialect,
2505            copy=copy,
2506            **opts,
2507        )
2508
2509    def group_by(
2510        self,
2511        *expressions: t.Optional[ExpOrStr],
2512        append: bool = True,
2513        dialect: DialectType = None,
2514        copy: bool = True,
2515        **opts,
2516    ) -> Select:
2517        """
2518        Set the GROUP BY expression.
2519
2520        Example:
2521            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2522            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2523
2524        Args:
2525            *expressions: the SQL code strings to parse.
2526                If a `Group` instance is passed, this is used as-is.
2527                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2528                If nothing is passed in then a group by is not applied to the expression
2529            append: if `True`, add to any existing expressions.
2530                Otherwise, this flattens all the `Group` expression into a single expression.
2531            dialect: the dialect used to parse the input expression.
2532            copy: if `False`, modify this expression instance in-place.
2533            opts: other options to use to parse the input expressions.
2534
2535        Returns:
2536            The modified Select expression.
2537        """
2538        if not expressions:
2539            return self if not copy else self.copy()
2540
2541        return _apply_child_list_builder(
2542            *expressions,
2543            instance=self,
2544            arg="group",
2545            append=append,
2546            copy=copy,
2547            prefix="GROUP BY",
2548            into=Group,
2549            dialect=dialect,
2550            **opts,
2551        )
2552
2553    def order_by(
2554        self,
2555        *expressions: t.Optional[ExpOrStr],
2556        append: bool = True,
2557        dialect: DialectType = None,
2558        copy: bool = True,
2559        **opts,
2560    ) -> Select:
2561        """
2562        Set the ORDER BY expression.
2563
2564        Example:
2565            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2566            'SELECT x FROM tbl ORDER BY x DESC'
2567
2568        Args:
2569            *expressions: the SQL code strings to parse.
2570                If a `Group` instance is passed, this is used as-is.
2571                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2572            append: if `True`, add to any existing expressions.
2573                Otherwise, this flattens all the `Order` expression into a single expression.
2574            dialect: the dialect used to parse the input expression.
2575            copy: if `False`, modify this expression instance in-place.
2576            opts: other options to use to parse the input expressions.
2577
2578        Returns:
2579            The modified Select expression.
2580        """
2581        return _apply_child_list_builder(
2582            *expressions,
2583            instance=self,
2584            arg="order",
2585            append=append,
2586            copy=copy,
2587            prefix="ORDER BY",
2588            into=Order,
2589            dialect=dialect,
2590            **opts,
2591        )
2592
2593    def sort_by(
2594        self,
2595        *expressions: t.Optional[ExpOrStr],
2596        append: bool = True,
2597        dialect: DialectType = None,
2598        copy: bool = True,
2599        **opts,
2600    ) -> Select:
2601        """
2602        Set the SORT BY expression.
2603
2604        Example:
2605            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2606            'SELECT x FROM tbl SORT BY x DESC'
2607
2608        Args:
2609            *expressions: the SQL code strings to parse.
2610                If a `Group` instance is passed, this is used as-is.
2611                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2612            append: if `True`, add to any existing expressions.
2613                Otherwise, this flattens all the `Order` expression into a single expression.
2614            dialect: the dialect used to parse the input expression.
2615            copy: if `False`, modify this expression instance in-place.
2616            opts: other options to use to parse the input expressions.
2617
2618        Returns:
2619            The modified Select expression.
2620        """
2621        return _apply_child_list_builder(
2622            *expressions,
2623            instance=self,
2624            arg="sort",
2625            append=append,
2626            copy=copy,
2627            prefix="SORT BY",
2628            into=Sort,
2629            dialect=dialect,
2630            **opts,
2631        )
2632
2633    def cluster_by(
2634        self,
2635        *expressions: t.Optional[ExpOrStr],
2636        append: bool = True,
2637        dialect: DialectType = None,
2638        copy: bool = True,
2639        **opts,
2640    ) -> Select:
2641        """
2642        Set the CLUSTER BY expression.
2643
2644        Example:
2645            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2646            'SELECT x FROM tbl CLUSTER BY x DESC'
2647
2648        Args:
2649            *expressions: the SQL code strings to parse.
2650                If a `Group` instance is passed, this is used as-is.
2651                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2652            append: if `True`, add to any existing expressions.
2653                Otherwise, this flattens all the `Order` expression into a single expression.
2654            dialect: the dialect used to parse the input expression.
2655            copy: if `False`, modify this expression instance in-place.
2656            opts: other options to use to parse the input expressions.
2657
2658        Returns:
2659            The modified Select expression.
2660        """
2661        return _apply_child_list_builder(
2662            *expressions,
2663            instance=self,
2664            arg="cluster",
2665            append=append,
2666            copy=copy,
2667            prefix="CLUSTER BY",
2668            into=Cluster,
2669            dialect=dialect,
2670            **opts,
2671        )
2672
2673    def limit(
2674        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2675    ) -> Select:
2676        """
2677        Set the LIMIT expression.
2678
2679        Example:
2680            >>> Select().from_("tbl").select("x").limit(10).sql()
2681            'SELECT x FROM tbl LIMIT 10'
2682
2683        Args:
2684            expression: the SQL code string to parse.
2685                This can also be an integer.
2686                If a `Limit` instance is passed, this is used as-is.
2687                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2688            dialect: the dialect used to parse the input expression.
2689            copy: if `False`, modify this expression instance in-place.
2690            opts: other options to use to parse the input expressions.
2691
2692        Returns:
2693            Select: the modified expression.
2694        """
2695        return _apply_builder(
2696            expression=expression,
2697            instance=self,
2698            arg="limit",
2699            into=Limit,
2700            prefix="LIMIT",
2701            dialect=dialect,
2702            copy=copy,
2703            **opts,
2704        )
2705
2706    def offset(
2707        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2708    ) -> Select:
2709        """
2710        Set the OFFSET expression.
2711
2712        Example:
2713            >>> Select().from_("tbl").select("x").offset(10).sql()
2714            'SELECT x FROM tbl OFFSET 10'
2715
2716        Args:
2717            expression: the SQL code string to parse.
2718                This can also be an integer.
2719                If a `Offset` instance is passed, this is used as-is.
2720                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2721            dialect: the dialect used to parse the input expression.
2722            copy: if `False`, modify this expression instance in-place.
2723            opts: other options to use to parse the input expressions.
2724
2725        Returns:
2726            The modified Select expression.
2727        """
2728        return _apply_builder(
2729            expression=expression,
2730            instance=self,
2731            arg="offset",
2732            into=Offset,
2733            prefix="OFFSET",
2734            dialect=dialect,
2735            copy=copy,
2736            **opts,
2737        )
2738
2739    def select(
2740        self,
2741        *expressions: t.Optional[ExpOrStr],
2742        append: bool = True,
2743        dialect: DialectType = None,
2744        copy: bool = True,
2745        **opts,
2746    ) -> Select:
2747        """
2748        Append to or set the SELECT expressions.
2749
2750        Example:
2751            >>> Select().select("x", "y").sql()
2752            'SELECT x, y'
2753
2754        Args:
2755            *expressions: the SQL code strings to parse.
2756                If an `Expression` instance is passed, it will be used as-is.
2757            append: if `True`, add to any existing expressions.
2758                Otherwise, this resets the expressions.
2759            dialect: the dialect used to parse the input expressions.
2760            copy: if `False`, modify this expression instance in-place.
2761            opts: other options to use to parse the input expressions.
2762
2763        Returns:
2764            The modified Select expression.
2765        """
2766        return _apply_list_builder(
2767            *expressions,
2768            instance=self,
2769            arg="expressions",
2770            append=append,
2771            dialect=dialect,
2772            copy=copy,
2773            **opts,
2774        )
2775
2776    def lateral(
2777        self,
2778        *expressions: t.Optional[ExpOrStr],
2779        append: bool = True,
2780        dialect: DialectType = None,
2781        copy: bool = True,
2782        **opts,
2783    ) -> Select:
2784        """
2785        Append to or set the LATERAL expressions.
2786
2787        Example:
2788            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2789            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2790
2791        Args:
2792            *expressions: the SQL code strings to parse.
2793                If an `Expression` instance is passed, it will be used as-is.
2794            append: if `True`, add to any existing expressions.
2795                Otherwise, this resets the expressions.
2796            dialect: the dialect used to parse the input expressions.
2797            copy: if `False`, modify this expression instance in-place.
2798            opts: other options to use to parse the input expressions.
2799
2800        Returns:
2801            The modified Select expression.
2802        """
2803        return _apply_list_builder(
2804            *expressions,
2805            instance=self,
2806            arg="laterals",
2807            append=append,
2808            into=Lateral,
2809            prefix="LATERAL VIEW",
2810            dialect=dialect,
2811            copy=copy,
2812            **opts,
2813        )
2814
2815    def join(
2816        self,
2817        expression: ExpOrStr,
2818        on: t.Optional[ExpOrStr] = None,
2819        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2820        append: bool = True,
2821        join_type: t.Optional[str] = None,
2822        join_alias: t.Optional[Identifier | str] = None,
2823        dialect: DialectType = None,
2824        copy: bool = True,
2825        **opts,
2826    ) -> Select:
2827        """
2828        Append to or set the JOIN expressions.
2829
2830        Example:
2831            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2832            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2833
2834            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2835            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2836
2837            Use `join_type` to change the type of join:
2838
2839            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2840            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2841
2842        Args:
2843            expression: the SQL code string to parse.
2844                If an `Expression` instance is passed, it will be used as-is.
2845            on: optionally specify the join "on" criteria as a SQL string.
2846                If an `Expression` instance is passed, it will be used as-is.
2847            using: optionally specify the join "using" criteria as a SQL string.
2848                If an `Expression` instance is passed, it will be used as-is.
2849            append: if `True`, add to any existing expressions.
2850                Otherwise, this resets the expressions.
2851            join_type: if set, alter the parsed join type.
2852            join_alias: an optional alias for the joined source.
2853            dialect: the dialect used to parse the input expressions.
2854            copy: if `False`, modify this expression instance in-place.
2855            opts: other options to use to parse the input expressions.
2856
2857        Returns:
2858            Select: the modified expression.
2859        """
2860        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2861
2862        try:
2863            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2864        except ParseError:
2865            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2866
2867        join = expression if isinstance(expression, Join) else Join(this=expression)
2868
2869        if isinstance(join.this, Select):
2870            join.this.replace(join.this.subquery())
2871
2872        if join_type:
2873            method: t.Optional[Token]
2874            side: t.Optional[Token]
2875            kind: t.Optional[Token]
2876
2877            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2878
2879            if method:
2880                join.set("method", method.text)
2881            if side:
2882                join.set("side", side.text)
2883            if kind:
2884                join.set("kind", kind.text)
2885
2886        if on:
2887            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2888            join.set("on", on)
2889
2890        if using:
2891            join = _apply_list_builder(
2892                *ensure_list(using),
2893                instance=join,
2894                arg="using",
2895                append=append,
2896                copy=copy,
2897                **opts,
2898            )
2899
2900        if join_alias:
2901            join.set("this", alias_(join.this, join_alias, table=True))
2902
2903        return _apply_list_builder(
2904            join,
2905            instance=self,
2906            arg="joins",
2907            append=append,
2908            copy=copy,
2909            **opts,
2910        )
2911
2912    def where(
2913        self,
2914        *expressions: t.Optional[ExpOrStr],
2915        append: bool = True,
2916        dialect: DialectType = None,
2917        copy: bool = True,
2918        **opts,
2919    ) -> Select:
2920        """
2921        Append to or set the WHERE expressions.
2922
2923        Example:
2924            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2925            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2926
2927        Args:
2928            *expressions: the SQL code strings to parse.
2929                If an `Expression` instance is passed, it will be used as-is.
2930                Multiple expressions are combined with an AND operator.
2931            append: if `True`, AND the new expressions to any existing expression.
2932                Otherwise, this resets the expression.
2933            dialect: the dialect used to parse the input expressions.
2934            copy: if `False`, modify this expression instance in-place.
2935            opts: other options to use to parse the input expressions.
2936
2937        Returns:
2938            Select: the modified expression.
2939        """
2940        return _apply_conjunction_builder(
2941            *expressions,
2942            instance=self,
2943            arg="where",
2944            append=append,
2945            into=Where,
2946            dialect=dialect,
2947            copy=copy,
2948            **opts,
2949        )
2950
2951    def having(
2952        self,
2953        *expressions: t.Optional[ExpOrStr],
2954        append: bool = True,
2955        dialect: DialectType = None,
2956        copy: bool = True,
2957        **opts,
2958    ) -> Select:
2959        """
2960        Append to or set the HAVING expressions.
2961
2962        Example:
2963            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2964            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2965
2966        Args:
2967            *expressions: the SQL code strings to parse.
2968                If an `Expression` instance is passed, it will be used as-is.
2969                Multiple expressions are combined with an AND operator.
2970            append: if `True`, AND the new expressions to any existing expression.
2971                Otherwise, this resets the expression.
2972            dialect: the dialect used to parse the input expressions.
2973            copy: if `False`, modify this expression instance in-place.
2974            opts: other options to use to parse the input expressions.
2975
2976        Returns:
2977            The modified Select expression.
2978        """
2979        return _apply_conjunction_builder(
2980            *expressions,
2981            instance=self,
2982            arg="having",
2983            append=append,
2984            into=Having,
2985            dialect=dialect,
2986            copy=copy,
2987            **opts,
2988        )
2989
2990    def window(
2991        self,
2992        *expressions: t.Optional[ExpOrStr],
2993        append: bool = True,
2994        dialect: DialectType = None,
2995        copy: bool = True,
2996        **opts,
2997    ) -> Select:
2998        return _apply_list_builder(
2999            *expressions,
3000            instance=self,
3001            arg="windows",
3002            append=append,
3003            into=Window,
3004            dialect=dialect,
3005            copy=copy,
3006            **opts,
3007        )
3008
3009    def qualify(
3010        self,
3011        *expressions: t.Optional[ExpOrStr],
3012        append: bool = True,
3013        dialect: DialectType = None,
3014        copy: bool = True,
3015        **opts,
3016    ) -> Select:
3017        return _apply_conjunction_builder(
3018            *expressions,
3019            instance=self,
3020            arg="qualify",
3021            append=append,
3022            into=Qualify,
3023            dialect=dialect,
3024            copy=copy,
3025            **opts,
3026        )
3027
3028    def distinct(
3029        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3030    ) -> Select:
3031        """
3032        Set the OFFSET expression.
3033
3034        Example:
3035            >>> Select().from_("tbl").select("x").distinct().sql()
3036            'SELECT DISTINCT x FROM tbl'
3037
3038        Args:
3039            ons: the expressions to distinct on
3040            distinct: whether the Select should be distinct
3041            copy: if `False`, modify this expression instance in-place.
3042
3043        Returns:
3044            Select: the modified expression.
3045        """
3046        instance = _maybe_copy(self, copy)
3047        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3048        instance.set("distinct", Distinct(on=on) if distinct else None)
3049        return instance
3050
3051    def ctas(
3052        self,
3053        table: ExpOrStr,
3054        properties: t.Optional[t.Dict] = None,
3055        dialect: DialectType = None,
3056        copy: bool = True,
3057        **opts,
3058    ) -> Create:
3059        """
3060        Convert this expression to a CREATE TABLE AS statement.
3061
3062        Example:
3063            >>> Select().select("*").from_("tbl").ctas("x").sql()
3064            'CREATE TABLE x AS SELECT * FROM tbl'
3065
3066        Args:
3067            table: the SQL code string to parse as the table name.
3068                If another `Expression` instance is passed, it will be used as-is.
3069            properties: an optional mapping of table properties
3070            dialect: the dialect used to parse the input table.
3071            copy: if `False`, modify this expression instance in-place.
3072            opts: other options to use to parse the input table.
3073
3074        Returns:
3075            The new Create expression.
3076        """
3077        instance = _maybe_copy(self, copy)
3078        table_expression = maybe_parse(
3079            table,
3080            into=Table,
3081            dialect=dialect,
3082            **opts,
3083        )
3084        properties_expression = None
3085        if properties:
3086            properties_expression = Properties.from_dict(properties)
3087
3088        return Create(
3089            this=table_expression,
3090            kind="table",
3091            expression=instance,
3092            properties=properties_expression,
3093        )
3094
3095    def lock(self, update: bool = True, copy: bool = True) -> Select:
3096        """
3097        Set the locking read mode for this expression.
3098
3099        Examples:
3100            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3101            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3102
3103            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3104            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3105
3106        Args:
3107            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3108            copy: if `False`, modify this expression instance in-place.
3109
3110        Returns:
3111            The modified expression.
3112        """
3113        inst = _maybe_copy(self, copy)
3114        inst.set("locks", [Lock(update=update)])
3115
3116        return inst
3117
3118    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3119        """
3120        Set hints for this expression.
3121
3122        Examples:
3123            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3124            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3125
3126        Args:
3127            hints: The SQL code strings to parse as the hints.
3128                If an `Expression` instance is passed, it will be used as-is.
3129            dialect: The dialect used to parse the hints.
3130            copy: If `False`, modify this expression instance in-place.
3131
3132        Returns:
3133            The modified expression.
3134        """
3135        inst = _maybe_copy(self, copy)
3136        inst.set(
3137            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3138        )
3139
3140        return inst
3141
3142    @property
3143    def named_selects(self) -> t.List[str]:
3144        return [e.output_name for e in self.expressions if e.alias_or_name]
3145
3146    @property
3147    def is_star(self) -> bool:
3148        return any(expression.is_star for expression in self.expressions)
3149
3150    @property
3151    def selects(self) -> t.List[Expression]:
3152        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def from_( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2477    def from_(
2478        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2479    ) -> Select:
2480        """
2481        Set the FROM expression.
2482
2483        Example:
2484            >>> Select().from_("tbl").select("x").sql()
2485            'SELECT x FROM tbl'
2486
2487        Args:
2488            expression : the SQL code strings to parse.
2489                If a `From` instance is passed, this is used as-is.
2490                If another `Expression` instance is passed, it will be wrapped in a `From`.
2491            dialect: the dialect used to parse the input expression.
2492            copy: if `False`, modify this expression instance in-place.
2493            opts: other options to use to parse the input expressions.
2494
2495        Returns:
2496            The modified Select expression.
2497        """
2498        return _apply_builder(
2499            expression=expression,
2500            instance=self,
2501            arg="from",
2502            into=From,
2503            prefix="FROM",
2504            dialect=dialect,
2505            copy=copy,
2506            **opts,
2507        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2509    def group_by(
2510        self,
2511        *expressions: t.Optional[ExpOrStr],
2512        append: bool = True,
2513        dialect: DialectType = None,
2514        copy: bool = True,
2515        **opts,
2516    ) -> Select:
2517        """
2518        Set the GROUP BY expression.
2519
2520        Example:
2521            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2522            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2523
2524        Args:
2525            *expressions: the SQL code strings to parse.
2526                If a `Group` instance is passed, this is used as-is.
2527                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2528                If nothing is passed in then a group by is not applied to the expression
2529            append: if `True`, add to any existing expressions.
2530                Otherwise, this flattens all the `Group` expression into a single expression.
2531            dialect: the dialect used to parse the input expression.
2532            copy: if `False`, modify this expression instance in-place.
2533            opts: other options to use to parse the input expressions.
2534
2535        Returns:
2536            The modified Select expression.
2537        """
2538        if not expressions:
2539            return self if not copy else self.copy()
2540
2541        return _apply_child_list_builder(
2542            *expressions,
2543            instance=self,
2544            arg="group",
2545            append=append,
2546            copy=copy,
2547            prefix="GROUP BY",
2548            into=Group,
2549            dialect=dialect,
2550            **opts,
2551        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2553    def order_by(
2554        self,
2555        *expressions: t.Optional[ExpOrStr],
2556        append: bool = True,
2557        dialect: DialectType = None,
2558        copy: bool = True,
2559        **opts,
2560    ) -> Select:
2561        """
2562        Set the ORDER BY expression.
2563
2564        Example:
2565            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2566            'SELECT x FROM tbl ORDER BY x DESC'
2567
2568        Args:
2569            *expressions: the SQL code strings to parse.
2570                If a `Group` instance is passed, this is used as-is.
2571                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2572            append: if `True`, add to any existing expressions.
2573                Otherwise, this flattens all the `Order` expression into a single expression.
2574            dialect: the dialect used to parse the input expression.
2575            copy: if `False`, modify this expression instance in-place.
2576            opts: other options to use to parse the input expressions.
2577
2578        Returns:
2579            The modified Select expression.
2580        """
2581        return _apply_child_list_builder(
2582            *expressions,
2583            instance=self,
2584            arg="order",
2585            append=append,
2586            copy=copy,
2587            prefix="ORDER BY",
2588            into=Order,
2589            dialect=dialect,
2590            **opts,
2591        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2593    def sort_by(
2594        self,
2595        *expressions: t.Optional[ExpOrStr],
2596        append: bool = True,
2597        dialect: DialectType = None,
2598        copy: bool = True,
2599        **opts,
2600    ) -> Select:
2601        """
2602        Set the SORT BY expression.
2603
2604        Example:
2605            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2606            'SELECT x FROM tbl SORT BY x DESC'
2607
2608        Args:
2609            *expressions: the SQL code strings to parse.
2610                If a `Group` instance is passed, this is used as-is.
2611                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2612            append: if `True`, add to any existing expressions.
2613                Otherwise, this flattens all the `Order` expression into a single expression.
2614            dialect: the dialect used to parse the input expression.
2615            copy: if `False`, modify this expression instance in-place.
2616            opts: other options to use to parse the input expressions.
2617
2618        Returns:
2619            The modified Select expression.
2620        """
2621        return _apply_child_list_builder(
2622            *expressions,
2623            instance=self,
2624            arg="sort",
2625            append=append,
2626            copy=copy,
2627            prefix="SORT BY",
2628            into=Sort,
2629            dialect=dialect,
2630            **opts,
2631        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2633    def cluster_by(
2634        self,
2635        *expressions: t.Optional[ExpOrStr],
2636        append: bool = True,
2637        dialect: DialectType = None,
2638        copy: bool = True,
2639        **opts,
2640    ) -> Select:
2641        """
2642        Set the CLUSTER BY expression.
2643
2644        Example:
2645            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2646            'SELECT x FROM tbl CLUSTER BY x DESC'
2647
2648        Args:
2649            *expressions: the SQL code strings to parse.
2650                If a `Group` instance is passed, this is used as-is.
2651                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2652            append: if `True`, add to any existing expressions.
2653                Otherwise, this flattens all the `Order` expression into a single expression.
2654            dialect: the dialect used to parse the input expression.
2655            copy: if `False`, modify this expression instance in-place.
2656            opts: other options to use to parse the input expressions.
2657
2658        Returns:
2659            The modified Select expression.
2660        """
2661        return _apply_child_list_builder(
2662            *expressions,
2663            instance=self,
2664            arg="cluster",
2665            append=append,
2666            copy=copy,
2667            prefix="CLUSTER BY",
2668            into=Cluster,
2669            dialect=dialect,
2670            **opts,
2671        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2673    def limit(
2674        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2675    ) -> Select:
2676        """
2677        Set the LIMIT expression.
2678
2679        Example:
2680            >>> Select().from_("tbl").select("x").limit(10).sql()
2681            'SELECT x FROM tbl LIMIT 10'
2682
2683        Args:
2684            expression: the SQL code string to parse.
2685                This can also be an integer.
2686                If a `Limit` instance is passed, this is used as-is.
2687                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2688            dialect: the dialect used to parse the input expression.
2689            copy: if `False`, modify this expression instance in-place.
2690            opts: other options to use to parse the input expressions.
2691
2692        Returns:
2693            Select: the modified expression.
2694        """
2695        return _apply_builder(
2696            expression=expression,
2697            instance=self,
2698            arg="limit",
2699            into=Limit,
2700            prefix="LIMIT",
2701            dialect=dialect,
2702            copy=copy,
2703            **opts,
2704        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2706    def offset(
2707        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2708    ) -> Select:
2709        """
2710        Set the OFFSET expression.
2711
2712        Example:
2713            >>> Select().from_("tbl").select("x").offset(10).sql()
2714            'SELECT x FROM tbl OFFSET 10'
2715
2716        Args:
2717            expression: the SQL code string to parse.
2718                This can also be an integer.
2719                If a `Offset` instance is passed, this is used as-is.
2720                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2721            dialect: the dialect used to parse the input expression.
2722            copy: if `False`, modify this expression instance in-place.
2723            opts: other options to use to parse the input expressions.
2724
2725        Returns:
2726            The modified Select expression.
2727        """
2728        return _apply_builder(
2729            expression=expression,
2730            instance=self,
2731            arg="offset",
2732            into=Offset,
2733            prefix="OFFSET",
2734            dialect=dialect,
2735            copy=copy,
2736            **opts,
2737        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2739    def select(
2740        self,
2741        *expressions: t.Optional[ExpOrStr],
2742        append: bool = True,
2743        dialect: DialectType = None,
2744        copy: bool = True,
2745        **opts,
2746    ) -> Select:
2747        """
2748        Append to or set the SELECT expressions.
2749
2750        Example:
2751            >>> Select().select("x", "y").sql()
2752            'SELECT x, y'
2753
2754        Args:
2755            *expressions: the SQL code strings to parse.
2756                If an `Expression` instance is passed, it will be used as-is.
2757            append: if `True`, add to any existing expressions.
2758                Otherwise, this resets the expressions.
2759            dialect: the dialect used to parse the input expressions.
2760            copy: if `False`, modify this expression instance in-place.
2761            opts: other options to use to parse the input expressions.
2762
2763        Returns:
2764            The modified Select expression.
2765        """
2766        return _apply_list_builder(
2767            *expressions,
2768            instance=self,
2769            arg="expressions",
2770            append=append,
2771            dialect=dialect,
2772            copy=copy,
2773            **opts,
2774        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2776    def lateral(
2777        self,
2778        *expressions: t.Optional[ExpOrStr],
2779        append: bool = True,
2780        dialect: DialectType = None,
2781        copy: bool = True,
2782        **opts,
2783    ) -> Select:
2784        """
2785        Append to or set the LATERAL expressions.
2786
2787        Example:
2788            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2789            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2790
2791        Args:
2792            *expressions: the SQL code strings to parse.
2793                If an `Expression` instance is passed, it will be used as-is.
2794            append: if `True`, add to any existing expressions.
2795                Otherwise, this resets the expressions.
2796            dialect: the dialect used to parse the input expressions.
2797            copy: if `False`, modify this expression instance in-place.
2798            opts: other options to use to parse the input expressions.
2799
2800        Returns:
2801            The modified Select expression.
2802        """
2803        return _apply_list_builder(
2804            *expressions,
2805            instance=self,
2806            arg="laterals",
2807            append=append,
2808            into=Lateral,
2809            prefix="LATERAL VIEW",
2810            dialect=dialect,
2811            copy=copy,
2812            **opts,
2813        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2815    def join(
2816        self,
2817        expression: ExpOrStr,
2818        on: t.Optional[ExpOrStr] = None,
2819        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2820        append: bool = True,
2821        join_type: t.Optional[str] = None,
2822        join_alias: t.Optional[Identifier | str] = None,
2823        dialect: DialectType = None,
2824        copy: bool = True,
2825        **opts,
2826    ) -> Select:
2827        """
2828        Append to or set the JOIN expressions.
2829
2830        Example:
2831            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2832            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2833
2834            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2835            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2836
2837            Use `join_type` to change the type of join:
2838
2839            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2840            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2841
2842        Args:
2843            expression: the SQL code string to parse.
2844                If an `Expression` instance is passed, it will be used as-is.
2845            on: optionally specify the join "on" criteria as a SQL string.
2846                If an `Expression` instance is passed, it will be used as-is.
2847            using: optionally specify the join "using" criteria as a SQL string.
2848                If an `Expression` instance is passed, it will be used as-is.
2849            append: if `True`, add to any existing expressions.
2850                Otherwise, this resets the expressions.
2851            join_type: if set, alter the parsed join type.
2852            join_alias: an optional alias for the joined source.
2853            dialect: the dialect used to parse the input expressions.
2854            copy: if `False`, modify this expression instance in-place.
2855            opts: other options to use to parse the input expressions.
2856
2857        Returns:
2858            Select: the modified expression.
2859        """
2860        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2861
2862        try:
2863            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2864        except ParseError:
2865            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2866
2867        join = expression if isinstance(expression, Join) else Join(this=expression)
2868
2869        if isinstance(join.this, Select):
2870            join.this.replace(join.this.subquery())
2871
2872        if join_type:
2873            method: t.Optional[Token]
2874            side: t.Optional[Token]
2875            kind: t.Optional[Token]
2876
2877            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2878
2879            if method:
2880                join.set("method", method.text)
2881            if side:
2882                join.set("side", side.text)
2883            if kind:
2884                join.set("kind", kind.text)
2885
2886        if on:
2887            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2888            join.set("on", on)
2889
2890        if using:
2891            join = _apply_list_builder(
2892                *ensure_list(using),
2893                instance=join,
2894                arg="using",
2895                append=append,
2896                copy=copy,
2897                **opts,
2898            )
2899
2900        if join_alias:
2901            join.set("this", alias_(join.this, join_alias, table=True))
2902
2903        return _apply_list_builder(
2904            join,
2905            instance=self,
2906            arg="joins",
2907            append=append,
2908            copy=copy,
2909            **opts,
2910        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2912    def where(
2913        self,
2914        *expressions: t.Optional[ExpOrStr],
2915        append: bool = True,
2916        dialect: DialectType = None,
2917        copy: bool = True,
2918        **opts,
2919    ) -> Select:
2920        """
2921        Append to or set the WHERE expressions.
2922
2923        Example:
2924            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2925            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2926
2927        Args:
2928            *expressions: the SQL code strings to parse.
2929                If an `Expression` instance is passed, it will be used as-is.
2930                Multiple expressions are combined with an AND operator.
2931            append: if `True`, AND the new expressions to any existing expression.
2932                Otherwise, this resets the expression.
2933            dialect: the dialect used to parse the input expressions.
2934            copy: if `False`, modify this expression instance in-place.
2935            opts: other options to use to parse the input expressions.
2936
2937        Returns:
2938            Select: the modified expression.
2939        """
2940        return _apply_conjunction_builder(
2941            *expressions,
2942            instance=self,
2943            arg="where",
2944            append=append,
2945            into=Where,
2946            dialect=dialect,
2947            copy=copy,
2948            **opts,
2949        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2951    def having(
2952        self,
2953        *expressions: t.Optional[ExpOrStr],
2954        append: bool = True,
2955        dialect: DialectType = None,
2956        copy: bool = True,
2957        **opts,
2958    ) -> Select:
2959        """
2960        Append to or set the HAVING expressions.
2961
2962        Example:
2963            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2964            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2965
2966        Args:
2967            *expressions: the SQL code strings to parse.
2968                If an `Expression` instance is passed, it will be used as-is.
2969                Multiple expressions are combined with an AND operator.
2970            append: if `True`, AND the new expressions to any existing expression.
2971                Otherwise, this resets the expression.
2972            dialect: the dialect used to parse the input expressions.
2973            copy: if `False`, modify this expression instance in-place.
2974            opts: other options to use to parse the input expressions.
2975
2976        Returns:
2977            The modified Select expression.
2978        """
2979        return _apply_conjunction_builder(
2980            *expressions,
2981            instance=self,
2982            arg="having",
2983            append=append,
2984            into=Having,
2985            dialect=dialect,
2986            copy=copy,
2987            **opts,
2988        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2990    def window(
2991        self,
2992        *expressions: t.Optional[ExpOrStr],
2993        append: bool = True,
2994        dialect: DialectType = None,
2995        copy: bool = True,
2996        **opts,
2997    ) -> Select:
2998        return _apply_list_builder(
2999            *expressions,
3000            instance=self,
3001            arg="windows",
3002            append=append,
3003            into=Window,
3004            dialect=dialect,
3005            copy=copy,
3006            **opts,
3007        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3009    def qualify(
3010        self,
3011        *expressions: t.Optional[ExpOrStr],
3012        append: bool = True,
3013        dialect: DialectType = None,
3014        copy: bool = True,
3015        **opts,
3016    ) -> Select:
3017        return _apply_conjunction_builder(
3018            *expressions,
3019            instance=self,
3020            arg="qualify",
3021            append=append,
3022            into=Qualify,
3023            dialect=dialect,
3024            copy=copy,
3025            **opts,
3026        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3028    def distinct(
3029        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3030    ) -> Select:
3031        """
3032        Set the OFFSET expression.
3033
3034        Example:
3035            >>> Select().from_("tbl").select("x").distinct().sql()
3036            'SELECT DISTINCT x FROM tbl'
3037
3038        Args:
3039            ons: the expressions to distinct on
3040            distinct: whether the Select should be distinct
3041            copy: if `False`, modify this expression instance in-place.
3042
3043        Returns:
3044            Select: the modified expression.
3045        """
3046        instance = _maybe_copy(self, copy)
3047        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3048        instance.set("distinct", Distinct(on=on) if distinct else None)
3049        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3051    def ctas(
3052        self,
3053        table: ExpOrStr,
3054        properties: t.Optional[t.Dict] = None,
3055        dialect: DialectType = None,
3056        copy: bool = True,
3057        **opts,
3058    ) -> Create:
3059        """
3060        Convert this expression to a CREATE TABLE AS statement.
3061
3062        Example:
3063            >>> Select().select("*").from_("tbl").ctas("x").sql()
3064            'CREATE TABLE x AS SELECT * FROM tbl'
3065
3066        Args:
3067            table: the SQL code string to parse as the table name.
3068                If another `Expression` instance is passed, it will be used as-is.
3069            properties: an optional mapping of table properties
3070            dialect: the dialect used to parse the input table.
3071            copy: if `False`, modify this expression instance in-place.
3072            opts: other options to use to parse the input table.
3073
3074        Returns:
3075            The new Create expression.
3076        """
3077        instance = _maybe_copy(self, copy)
3078        table_expression = maybe_parse(
3079            table,
3080            into=Table,
3081            dialect=dialect,
3082            **opts,
3083        )
3084        properties_expression = None
3085        if properties:
3086            properties_expression = Properties.from_dict(properties)
3087
3088        return Create(
3089            this=table_expression,
3090            kind="table",
3091            expression=instance,
3092            properties=properties_expression,
3093        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3095    def lock(self, update: bool = True, copy: bool = True) -> Select:
3096        """
3097        Set the locking read mode for this expression.
3098
3099        Examples:
3100            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3101            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3102
3103            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3104            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3105
3106        Args:
3107            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3108            copy: if `False`, modify this expression instance in-place.
3109
3110        Returns:
3111            The modified expression.
3112        """
3113        inst = _maybe_copy(self, copy)
3114        inst.set("locks", [Lock(update=update)])
3115
3116        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3118    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3119        """
3120        Set hints for this expression.
3121
3122        Examples:
3123            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3124            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3125
3126        Args:
3127            hints: The SQL code strings to parse as the hints.
3128                If an `Expression` instance is passed, it will be used as-is.
3129            dialect: The dialect used to parse the hints.
3130            copy: If `False`, modify this expression instance in-place.
3131
3132        Returns:
3133            The modified expression.
3134        """
3135        inst = _maybe_copy(self, copy)
3136        inst.set(
3137            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3138        )
3139
3140        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3155class Subquery(DerivedTable, Unionable):
3156    arg_types = {
3157        "this": True,
3158        "alias": False,
3159        "with": False,
3160        **QUERY_MODIFIERS,
3161    }
3162
3163    def unnest(self):
3164        """
3165        Returns the first non subquery.
3166        """
3167        expression = self
3168        while isinstance(expression, Subquery):
3169            expression = expression.this
3170        return expression
3171
3172    @property
3173    def is_star(self) -> bool:
3174        return self.this.is_star
3175
3176    @property
3177    def output_name(self) -> str:
3178        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3163    def unnest(self):
3164        """
3165        Returns the first non subquery.
3166        """
3167        expression = self
3168        while isinstance(expression, Subquery):
3169            expression = expression.this
3170        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3181class TableSample(Expression):
3182    arg_types = {
3183        "this": False,
3184        "method": False,
3185        "bucket_numerator": False,
3186        "bucket_denominator": False,
3187        "bucket_field": False,
3188        "percent": False,
3189        "rows": False,
3190        "size": False,
3191        "seed": False,
3192        "kind": False,
3193    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3196class Tag(Expression):
3197    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3198
3199    arg_types = {
3200        "this": False,
3201        "prefix": False,
3202        "postfix": False,
3203    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3208class Pivot(Expression):
3209    arg_types = {
3210        "this": False,
3211        "alias": False,
3212        "expressions": True,
3213        "field": False,
3214        "unpivot": False,
3215        "using": False,
3216        "group": False,
3217        "columns": False,
3218    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3221class Window(Expression):
3222    arg_types = {
3223        "this": True,
3224        "partition_by": False,
3225        "order": False,
3226        "spec": False,
3227        "alias": False,
3228        "over": False,
3229        "first": False,
3230    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3233class WindowSpec(Expression):
3234    arg_types = {
3235        "kind": False,
3236        "start": False,
3237        "start_side": False,
3238        "end": False,
3239        "end_side": False,
3240    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3243class Where(Expression):
3244    pass
key = 'where'
class Star(Expression):
3247class Star(Expression):
3248    arg_types = {"except": False, "replace": False}
3249
3250    @property
3251    def name(self) -> str:
3252        return "*"
3253
3254    @property
3255    def output_name(self) -> str:
3256        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3259class Parameter(Condition):
3260    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3263class SessionParameter(Condition):
3264    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3267class Placeholder(Condition):
3268    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3271class Null(Condition):
3272    arg_types: t.Dict[str, t.Any] = {}
3273
3274    @property
3275    def name(self) -> str:
3276        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3279class Boolean(Condition):
3280    pass
key = 'boolean'
class DataTypeSize(Expression):
3283class DataTypeSize(Expression):
3284    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3287class DataType(Expression):
3288    arg_types = {
3289        "this": True,
3290        "expressions": False,
3291        "nested": False,
3292        "values": False,
3293        "prefix": False,
3294    }
3295
3296    class Type(AutoName):
3297        ARRAY = auto()
3298        BIGDECIMAL = auto()
3299        BIGINT = auto()
3300        BIGSERIAL = auto()
3301        BINARY = auto()
3302        BIT = auto()
3303        BOOLEAN = auto()
3304        CHAR = auto()
3305        DATE = auto()
3306        DATETIME = auto()
3307        DATETIME64 = auto()
3308        ENUM = auto()
3309        INT4RANGE = auto()
3310        INT4MULTIRANGE = auto()
3311        INT8RANGE = auto()
3312        INT8MULTIRANGE = auto()
3313        NUMRANGE = auto()
3314        NUMMULTIRANGE = auto()
3315        TSRANGE = auto()
3316        TSMULTIRANGE = auto()
3317        TSTZRANGE = auto()
3318        TSTZMULTIRANGE = auto()
3319        DATERANGE = auto()
3320        DATEMULTIRANGE = auto()
3321        DECIMAL = auto()
3322        DOUBLE = auto()
3323        FLOAT = auto()
3324        GEOGRAPHY = auto()
3325        GEOMETRY = auto()
3326        HLLSKETCH = auto()
3327        HSTORE = auto()
3328        IMAGE = auto()
3329        INET = auto()
3330        INT = auto()
3331        INT128 = auto()
3332        INT256 = auto()
3333        INTERVAL = auto()
3334        JSON = auto()
3335        JSONB = auto()
3336        LONGBLOB = auto()
3337        LONGTEXT = auto()
3338        MAP = auto()
3339        MEDIUMBLOB = auto()
3340        MEDIUMTEXT = auto()
3341        MONEY = auto()
3342        NCHAR = auto()
3343        NULL = auto()
3344        NULLABLE = auto()
3345        NVARCHAR = auto()
3346        OBJECT = auto()
3347        ROWVERSION = auto()
3348        SERIAL = auto()
3349        SET = auto()
3350        SMALLINT = auto()
3351        SMALLMONEY = auto()
3352        SMALLSERIAL = auto()
3353        STRUCT = auto()
3354        SUPER = auto()
3355        TEXT = auto()
3356        TIME = auto()
3357        TIMESTAMP = auto()
3358        TIMESTAMPTZ = auto()
3359        TIMESTAMPLTZ = auto()
3360        TINYINT = auto()
3361        UBIGINT = auto()
3362        UINT = auto()
3363        USMALLINT = auto()
3364        UTINYINT = auto()
3365        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3366        UINT128 = auto()
3367        UINT256 = auto()
3368        UNIQUEIDENTIFIER = auto()
3369        USERDEFINED = "USER-DEFINED"
3370        UUID = auto()
3371        VARBINARY = auto()
3372        VARCHAR = auto()
3373        VARIANT = auto()
3374        XML = auto()
3375
3376    TEXT_TYPES = {
3377        Type.CHAR,
3378        Type.NCHAR,
3379        Type.VARCHAR,
3380        Type.NVARCHAR,
3381        Type.TEXT,
3382    }
3383
3384    INTEGER_TYPES = {
3385        Type.INT,
3386        Type.TINYINT,
3387        Type.SMALLINT,
3388        Type.BIGINT,
3389        Type.INT128,
3390        Type.INT256,
3391    }
3392
3393    FLOAT_TYPES = {
3394        Type.FLOAT,
3395        Type.DOUBLE,
3396    }
3397
3398    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3399
3400    TEMPORAL_TYPES = {
3401        Type.TIME,
3402        Type.TIMESTAMP,
3403        Type.TIMESTAMPTZ,
3404        Type.TIMESTAMPLTZ,
3405        Type.DATE,
3406        Type.DATETIME,
3407        Type.DATETIME64,
3408    }
3409
3410    META_TYPES = {"UNKNOWN", "NULL"}
3411
3412    @classmethod
3413    def build(
3414        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3415    ) -> DataType:
3416        from sqlglot import parse_one
3417
3418        if isinstance(dtype, str):
3419            upper = dtype.upper()
3420            if upper in DataType.META_TYPES:
3421                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3422            else:
3423                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3424
3425            if data_type_exp is None:
3426                raise ValueError(f"Unparsable data type value: {dtype}")
3427        elif isinstance(dtype, DataType.Type):
3428            data_type_exp = DataType(this=dtype)
3429        elif isinstance(dtype, DataType):
3430            return dtype
3431        else:
3432            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3433
3434        return DataType(**{**data_type_exp.args, **kwargs})
3435
3436    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3437        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATETIME: 'DATETIME'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3412    @classmethod
3413    def build(
3414        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3415    ) -> DataType:
3416        from sqlglot import parse_one
3417
3418        if isinstance(dtype, str):
3419            upper = dtype.upper()
3420            if upper in DataType.META_TYPES:
3421                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3422            else:
3423                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3424
3425            if data_type_exp is None:
3426                raise ValueError(f"Unparsable data type value: {dtype}")
3427        elif isinstance(dtype, DataType.Type):
3428            data_type_exp = DataType(this=dtype)
3429        elif isinstance(dtype, DataType):
3430            return dtype
3431        else:
3432            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3433
3434        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3436    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3437        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3296    class Type(AutoName):
3297        ARRAY = auto()
3298        BIGDECIMAL = auto()
3299        BIGINT = auto()
3300        BIGSERIAL = auto()
3301        BINARY = auto()
3302        BIT = auto()
3303        BOOLEAN = auto()
3304        CHAR = auto()
3305        DATE = auto()
3306        DATETIME = auto()
3307        DATETIME64 = auto()
3308        ENUM = auto()
3309        INT4RANGE = auto()
3310        INT4MULTIRANGE = auto()
3311        INT8RANGE = auto()
3312        INT8MULTIRANGE = auto()
3313        NUMRANGE = auto()
3314        NUMMULTIRANGE = auto()
3315        TSRANGE = auto()
3316        TSMULTIRANGE = auto()
3317        TSTZRANGE = auto()
3318        TSTZMULTIRANGE = auto()
3319        DATERANGE = auto()
3320        DATEMULTIRANGE = auto()
3321        DECIMAL = auto()
3322        DOUBLE = auto()
3323        FLOAT = auto()
3324        GEOGRAPHY = auto()
3325        GEOMETRY = auto()
3326        HLLSKETCH = auto()
3327        HSTORE = auto()
3328        IMAGE = auto()
3329        INET = auto()
3330        INT = auto()
3331        INT128 = auto()
3332        INT256 = auto()
3333        INTERVAL = auto()
3334        JSON = auto()
3335        JSONB = auto()
3336        LONGBLOB = auto()
3337        LONGTEXT = auto()
3338        MAP = auto()
3339        MEDIUMBLOB = auto()
3340        MEDIUMTEXT = auto()
3341        MONEY = auto()
3342        NCHAR = auto()
3343        NULL = auto()
3344        NULLABLE = auto()
3345        NVARCHAR = auto()
3346        OBJECT = auto()
3347        ROWVERSION = auto()
3348        SERIAL = auto()
3349        SET = auto()
3350        SMALLINT = auto()
3351        SMALLMONEY = auto()
3352        SMALLSERIAL = auto()
3353        STRUCT = auto()
3354        SUPER = auto()
3355        TEXT = auto()
3356        TIME = auto()
3357        TIMESTAMP = auto()
3358        TIMESTAMPTZ = auto()
3359        TIMESTAMPLTZ = auto()
3360        TINYINT = auto()
3361        UBIGINT = auto()
3362        UINT = auto()
3363        USMALLINT = auto()
3364        UTINYINT = auto()
3365        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3366        UINT128 = auto()
3367        UINT256 = auto()
3368        UNIQUEIDENTIFIER = auto()
3369        USERDEFINED = "USER-DEFINED"
3370        UUID = auto()
3371        VARBINARY = auto()
3372        VARCHAR = auto()
3373        VARIANT = auto()
3374        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3441class PseudoType(Expression):
3442    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3446class SubqueryPredicate(Predicate):
3447    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3450class All(SubqueryPredicate):
3451    pass
key = 'all'
class Any(SubqueryPredicate):
3454class Any(SubqueryPredicate):
3455    pass
key = 'any'
class Exists(SubqueryPredicate):
3458class Exists(SubqueryPredicate):
3459    pass
key = 'exists'
class Command(Expression):
3464class Command(Expression):
3465    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3468class Transaction(Expression):
3469    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3472class Commit(Expression):
3473    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3476class Rollback(Expression):
3477    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3480class AlterTable(Expression):
3481    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3484class AddConstraint(Expression):
3485    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3488class DropPartition(Expression):
3489    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3493class Binary(Condition):
3494    arg_types = {"this": True, "expression": True}
3495
3496    @property
3497    def left(self):
3498        return self.this
3499
3500    @property
3501    def right(self):
3502        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3505class Add(Binary):
3506    pass
key = 'add'
class Connector(Binary):
3509class Connector(Binary):
3510    pass
key = 'connector'
class And(Connector):
3513class And(Connector):
3514    pass
key = 'and'
class Or(Connector):
3517class Or(Connector):
3518    pass
key = 'or'
class BitwiseAnd(Binary):
3521class BitwiseAnd(Binary):
3522    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3525class BitwiseLeftShift(Binary):
3526    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3529class BitwiseOr(Binary):
3530    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3533class BitwiseRightShift(Binary):
3534    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3537class BitwiseXor(Binary):
3538    pass
key = 'bitwisexor'
class Div(Binary):
3541class Div(Binary):
3542    pass
key = 'div'
class Overlaps(Binary):
3545class Overlaps(Binary):
3546    pass
key = 'overlaps'
class Dot(Binary):
3549class Dot(Binary):
3550    @property
3551    def name(self) -> str:
3552        return self.expression.name
3553
3554    @property
3555    def output_name(self) -> str:
3556        return self.name
3557
3558    @classmethod
3559    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3560        """Build a Dot object with a sequence of expressions."""
3561        if len(expressions) < 2:
3562            raise ValueError(f"Dot requires >= 2 expressions.")
3563
3564        a, b, *expressions = expressions
3565        dot = Dot(this=a, expression=b)
3566
3567        for expression in expressions:
3568            dot = Dot(this=dot, expression=expression)
3569
3570        return dot
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3558    @classmethod
3559    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3560        """Build a Dot object with a sequence of expressions."""
3561        if len(expressions) < 2:
3562            raise ValueError(f"Dot requires >= 2 expressions.")
3563
3564        a, b, *expressions = expressions
3565        dot = Dot(this=a, expression=b)
3566
3567        for expression in expressions:
3568            dot = Dot(this=dot, expression=expression)
3569
3570        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3573class DPipe(Binary):
3574    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3577class SafeDPipe(DPipe):
3578    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3581class EQ(Binary, Predicate):
3582    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3585class NullSafeEQ(Binary, Predicate):
3586    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3589class NullSafeNEQ(Binary, Predicate):
3590    pass
key = 'nullsafeneq'
class Distance(Binary):
3593class Distance(Binary):
3594    pass
key = 'distance'
class Escape(Binary):
3597class Escape(Binary):
3598    pass
key = 'escape'
class Glob(Binary, Predicate):
3601class Glob(Binary, Predicate):
3602    pass
key = 'glob'
class GT(Binary, Predicate):
3605class GT(Binary, Predicate):
3606    pass
key = 'gt'
class GTE(Binary, Predicate):
3609class GTE(Binary, Predicate):
3610    pass
key = 'gte'
class ILike(Binary, Predicate):
3613class ILike(Binary, Predicate):
3614    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3617class ILikeAny(Binary, Predicate):
3618    pass
key = 'ilikeany'
class IntDiv(Binary):
3621class IntDiv(Binary):
3622    pass
key = 'intdiv'
class Is(Binary, Predicate):
3625class Is(Binary, Predicate):
3626    pass
key = 'is'
class Kwarg(Binary):
3629class Kwarg(Binary):
3630    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key = 'kwarg'
class Like(Binary, Predicate):
3633class Like(Binary, Predicate):
3634    pass
key = 'like'
class LikeAny(Binary, Predicate):
3637class LikeAny(Binary, Predicate):
3638    pass
key = 'likeany'
class LT(Binary, Predicate):
3641class LT(Binary, Predicate):
3642    pass
key = 'lt'
class LTE(Binary, Predicate):
3645class LTE(Binary, Predicate):
3646    pass
key = 'lte'
class Mod(Binary):
3649class Mod(Binary):
3650    pass
key = 'mod'
class Mul(Binary):
3653class Mul(Binary):
3654    pass
key = 'mul'
class NEQ(Binary, Predicate):
3657class NEQ(Binary, Predicate):
3658    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3661class SimilarTo(Binary, Predicate):
3662    pass
key = 'similarto'
class Slice(Binary):
3665class Slice(Binary):
3666    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3669class Sub(Binary):
3670    pass
key = 'sub'
class ArrayOverlaps(Binary):
3673class ArrayOverlaps(Binary):
3674    pass
key = 'arrayoverlaps'
class Unary(Condition):
3679class Unary(Condition):
3680    pass
key = 'unary'
class BitwiseNot(Unary):
3683class BitwiseNot(Unary):
3684    pass
key = 'bitwisenot'
class Not(Unary):
3687class Not(Unary):
3688    pass
key = 'not'
class Paren(Unary):
3691class Paren(Unary):
3692    arg_types = {"this": True, "with": False}
3693
3694    @property
3695    def output_name(self) -> str:
3696        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3699class Neg(Unary):
3700    pass
key = 'neg'
class Alias(Expression):
3703class Alias(Expression):
3704    arg_types = {"this": True, "alias": False}
3705
3706    @property
3707    def output_name(self) -> str:
3708        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3711class Aliases(Expression):
3712    arg_types = {"this": True, "expressions": True}
3713
3714    @property
3715    def aliases(self):
3716        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3719class AtTimeZone(Expression):
3720    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3723class Between(Predicate):
3724    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3727class Bracket(Condition):
3728    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3731class SafeBracket(Bracket):
3732    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
3735class Distinct(Expression):
3736    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3739class In(Predicate):
3740    arg_types = {
3741        "this": True,
3742        "expressions": False,
3743        "query": False,
3744        "unnest": False,
3745        "field": False,
3746        "is_global": False,
3747    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3750class TimeUnit(Expression):
3751    """Automatically converts unit arg into a var."""
3752
3753    arg_types = {"unit": False}
3754
3755    def __init__(self, **args):
3756        unit = args.get("unit")
3757        if isinstance(unit, (Column, Literal)):
3758            args["unit"] = Var(this=unit.name)
3759        elif isinstance(unit, Week):
3760            unit.set("this", Var(this=unit.this.name))
3761
3762        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3755    def __init__(self, **args):
3756        unit = args.get("unit")
3757        if isinstance(unit, (Column, Literal)):
3758            args["unit"] = Var(this=unit.name)
3759        elif isinstance(unit, Week):
3760            unit.set("this", Var(this=unit.this.name))
3761
3762        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3765class Interval(TimeUnit):
3766    arg_types = {"this": False, "unit": False}
3767
3768    @property
3769    def unit(self) -> t.Optional[Var]:
3770        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3773class IgnoreNulls(Expression):
3774    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3777class RespectNulls(Expression):
3778    pass
key = 'respectnulls'
class Func(Condition):
3782class Func(Condition):
3783    """
3784    The base class for all function expressions.
3785
3786    Attributes:
3787        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3788            treated as a variable length argument and the argument's value will be stored as a list.
3789        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3790            for this function expression. These values are used to map this node to a name during parsing
3791            as well as to provide the function's name during SQL string generation. By default the SQL
3792            name is set to the expression's class name transformed to snake case.
3793    """
3794
3795    is_var_len_args = False
3796
3797    @classmethod
3798    def from_arg_list(cls, args):
3799        if cls.is_var_len_args:
3800            all_arg_keys = list(cls.arg_types)
3801            # If this function supports variable length argument treat the last argument as such.
3802            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3803            num_non_var = len(non_var_len_arg_keys)
3804
3805            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3806            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3807        else:
3808            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3809
3810        return cls(**args_dict)
3811
3812    @classmethod
3813    def sql_names(cls):
3814        if cls is Func:
3815            raise NotImplementedError(
3816                "SQL name is only supported by concrete function implementations"
3817            )
3818        if "_sql_names" not in cls.__dict__:
3819            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3820        return cls._sql_names
3821
3822    @classmethod
3823    def sql_name(cls):
3824        return cls.sql_names()[0]
3825
3826    @classmethod
3827    def default_parser_mappings(cls):
3828        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
3797    @classmethod
3798    def from_arg_list(cls, args):
3799        if cls.is_var_len_args:
3800            all_arg_keys = list(cls.arg_types)
3801            # If this function supports variable length argument treat the last argument as such.
3802            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3803            num_non_var = len(non_var_len_arg_keys)
3804
3805            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3806            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3807        else:
3808            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3809
3810        return cls(**args_dict)
@classmethod
def sql_names(cls):
3812    @classmethod
3813    def sql_names(cls):
3814        if cls is Func:
3815            raise NotImplementedError(
3816                "SQL name is only supported by concrete function implementations"
3817            )
3818        if "_sql_names" not in cls.__dict__:
3819            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3820        return cls._sql_names
@classmethod
def sql_name(cls):
3822    @classmethod
3823    def sql_name(cls):
3824        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3826    @classmethod
3827    def default_parser_mappings(cls):
3828        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3831class AggFunc(Func):
3832    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3835class ParameterizedAgg(AggFunc):
3836    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3839class Abs(Func):
3840    pass
key = 'abs'
class Anonymous(Func):
3843class Anonymous(Func):
3844    arg_types = {"this": True, "expressions": False}
3845    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3850class Hll(AggFunc):
3851    arg_types = {"this": True, "expressions": False}
3852    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3855class ApproxDistinct(AggFunc):
3856    arg_types = {"this": True, "accuracy": False}
3857    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3860class Array(Func):
3861    arg_types = {"expressions": False}
3862    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3866class ToChar(Func):
3867    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3870class GenerateSeries(Func):
3871    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3874class ArrayAgg(AggFunc):
3875    pass
key = 'arrayagg'
class ArrayAll(Func):
3878class ArrayAll(Func):
3879    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3882class ArrayAny(Func):
3883    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3886class ArrayConcat(Func):
3887    arg_types = {"this": True, "expressions": False}
3888    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3891class ArrayContains(Binary, Func):
3892    pass
key = 'arraycontains'
class ArrayContained(Binary):
3895class ArrayContained(Binary):
3896    pass
key = 'arraycontained'
class ArrayFilter(Func):
3899class ArrayFilter(Func):
3900    arg_types = {"this": True, "expression": True}
3901    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3904class ArrayJoin(Func):
3905    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3908class ArraySize(Func):
3909    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3912class ArraySort(Func):
3913    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3916class ArraySum(Func):
3917    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3920class ArrayUnionAgg(AggFunc):
3921    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3924class Avg(AggFunc):
3925    pass
key = 'avg'
class AnyValue(AggFunc):
3928class AnyValue(AggFunc):
3929    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3932class Case(Func):
3933    arg_types = {"this": False, "ifs": True, "default": False}
3934
3935    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3936        instance = _maybe_copy(self, copy)
3937        instance.append(
3938            "ifs",
3939            If(
3940                this=maybe_parse(condition, copy=copy, **opts),
3941                true=maybe_parse(then, copy=copy, **opts),
3942            ),
3943        )
3944        return instance
3945
3946    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3947        instance = _maybe_copy(self, copy)
3948        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3949        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3935    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3936        instance = _maybe_copy(self, copy)
3937        instance.append(
3938            "ifs",
3939            If(
3940                this=maybe_parse(condition, copy=copy, **opts),
3941                true=maybe_parse(then, copy=copy, **opts),
3942            ),
3943        )
3944        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3946    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3947        instance = _maybe_copy(self, copy)
3948        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3949        return instance
key = 'case'
class Cast(Func):
3952class Cast(Func):
3953    arg_types = {"this": True, "to": True, "format": False}
3954
3955    @property
3956    def name(self) -> str:
3957        return self.this.name
3958
3959    @property
3960    def to(self) -> DataType:
3961        return self.args["to"]
3962
3963    @property
3964    def output_name(self) -> str:
3965        return self.name
3966
3967    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3968        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3967    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3968        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3971class CastToStrType(Func):
3972    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3975class Collate(Binary):
3976    pass
key = 'collate'
class TryCast(Cast):
3979class TryCast(Cast):
3980    pass
key = 'trycast'
class Ceil(Func):
3983class Ceil(Func):
3984    arg_types = {"this": True, "decimals": False}
3985    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3988class Coalesce(Func):
3989    arg_types = {"this": True, "expressions": False}
3990    is_var_len_args = True
3991    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3994class Concat(Func):
3995    arg_types = {"expressions": True}
3996    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3999class SafeConcat(Concat):
4000    pass
key = 'safeconcat'
class ConcatWs(Concat):
4003class ConcatWs(Concat):
4004    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4007class Count(AggFunc):
4008    arg_types = {"this": False, "expressions": False}
4009    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4012class CountIf(AggFunc):
4013    pass
key = 'countif'
class CurrentDate(Func):
4016class CurrentDate(Func):
4017    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4020class CurrentDatetime(Func):
4021    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4024class CurrentTime(Func):
4025    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4028class CurrentTimestamp(Func):
4029    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4032class CurrentUser(Func):
4033    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4036class DateAdd(Func, TimeUnit):
4037    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4040class DateSub(Func, TimeUnit):
4041    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4044class DateDiff(Func, TimeUnit):
4045    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4046    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4049class DateTrunc(Func):
4050    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4053class DatetimeAdd(Func, TimeUnit):
4054    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4057class DatetimeSub(Func, TimeUnit):
4058    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4061class DatetimeDiff(Func, TimeUnit):
4062    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4065class DatetimeTrunc(Func, TimeUnit):
4066    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4069class DayOfWeek(Func):
4070    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4073class DayOfMonth(Func):
4074    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4077class DayOfYear(Func):
4078    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4081class WeekOfYear(Func):
4082    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4085class LastDateOfMonth(Func):
4086    pass
key = 'lastdateofmonth'
class Extract(Func):
4089class Extract(Func):
4090    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4093class TimestampAdd(Func, TimeUnit):
4094    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4097class TimestampSub(Func, TimeUnit):
4098    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4101class TimestampDiff(Func, TimeUnit):
4102    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4105class TimestampTrunc(Func, TimeUnit):
4106    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4109class TimeAdd(Func, TimeUnit):
4110    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4113class TimeSub(Func, TimeUnit):
4114    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4117class TimeDiff(Func, TimeUnit):
4118    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4121class TimeTrunc(Func, TimeUnit):
4122    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4125class DateFromParts(Func):
4126    _sql_names = ["DATEFROMPARTS"]
4127    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4130class DateStrToDate(Func):
4131    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4134class DateToDateStr(Func):
4135    pass
key = 'datetodatestr'
class DateToDi(Func):
4138class DateToDi(Func):
4139    pass
key = 'datetodi'
class Date(Func):
4143class Date(Func):
4144    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4147class Day(Func):
4148    pass
key = 'day'
class Decode(Func):
4151class Decode(Func):
4152    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4155class DiToDate(Func):
4156    pass
key = 'ditodate'
class Encode(Func):
4159class Encode(Func):
4160    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4163class Exp(Func):
4164    pass
key = 'exp'
class Explode(Func):
4167class Explode(Func):
4168    pass
key = 'explode'
class Floor(Func):
4171class Floor(Func):
4172    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4175class FromBase64(Func):
4176    pass
key = 'frombase64'
class ToBase64(Func):
4179class ToBase64(Func):
4180    pass
key = 'tobase64'
class Greatest(Func):
4183class Greatest(Func):
4184    arg_types = {"this": True, "expressions": False}
4185    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4188class GroupConcat(Func):
4189    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4192class Hex(Func):
4193    pass
key = 'hex'
class If(Func):
4196class If(Func):
4197    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4200class Initcap(Func):
4201    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4204class JSONKeyValue(Expression):
4205    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4208class JSONObject(Func):
4209    arg_types = {
4210        "expressions": False,
4211        "null_handling": False,
4212        "unique_keys": False,
4213        "return_type": False,
4214        "format_json": False,
4215        "encoding": False,
4216    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4219class OpenJSONColumnDef(Expression):
4220    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4223class OpenJSON(Func):
4224    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4227class JSONBContains(Binary):
4228    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4231class JSONExtract(Binary, Func):
4232    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4235class JSONExtractScalar(JSONExtract):
4236    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4239class JSONBExtract(JSONExtract):
4240    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4243class JSONBExtractScalar(JSONExtract):
4244    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4247class JSONFormat(Func):
4248    arg_types = {"this": False, "options": False}
4249    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4253class JSONArrayContains(Binary, Predicate, Func):
4254    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4257class Least(Func):
4258    arg_types = {"this": True, "expressions": False}
4259    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4262class Left(Func):
4263    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4270class Length(Func):
4271    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4274class Levenshtein(Func):
4275    arg_types = {
4276        "this": True,
4277        "expression": False,
4278        "ins_cost": False,
4279        "del_cost": False,
4280        "sub_cost": False,
4281    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4284class Ln(Func):
4285    pass
key = 'ln'
class Log(Func):
4288class Log(Func):
4289    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4292class Log2(Func):
4293    pass
key = 'log2'
class Log10(Func):
4296class Log10(Func):
4297    pass
key = 'log10'
class LogicalOr(AggFunc):
4300class LogicalOr(AggFunc):
4301    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4304class LogicalAnd(AggFunc):
4305    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4308class Lower(Func):
4309    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4312class Map(Func):
4313    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4316class MapFromEntries(Func):
4317    pass
key = 'mapfromentries'
class StarMap(Func):
4320class StarMap(Func):
4321    pass
key = 'starmap'
class VarMap(Func):
4324class VarMap(Func):
4325    arg_types = {"keys": True, "values": True}
4326    is_var_len_args = True
4327
4328    @property
4329    def keys(self) -> t.List[Expression]:
4330        return self.args["keys"].expressions
4331
4332    @property
4333    def values(self) -> t.List[Expression]:
4334        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4338class MatchAgainst(Func):
4339    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4342class Max(AggFunc):
4343    arg_types = {"this": True, "expressions": False}
4344    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4347class MD5(Func):
4348    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4352class MD5Digest(Func):
4353    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4356class Min(AggFunc):
4357    arg_types = {"this": True, "expressions": False}
4358    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4361class Month(Func):
4362    pass
key = 'month'
class Nvl2(Func):
4365class Nvl2(Func):
4366    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4369class Posexplode(Func):
4370    pass
key = 'posexplode'
class Pow(Binary, Func):
4373class Pow(Binary, Func):
4374    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4377class PercentileCont(AggFunc):
4378    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4381class PercentileDisc(AggFunc):
4382    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4385class Quantile(AggFunc):
4386    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4389class ApproxQuantile(Quantile):
4390    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4393class RangeN(Func):
4394    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4397class ReadCSV(Func):
4398    _sql_names = ["READ_CSV"]
4399    is_var_len_args = True
4400    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4403class Reduce(Func):
4404    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4407class RegexpExtract(Func):
4408    arg_types = {
4409        "this": True,
4410        "expression": True,
4411        "position": False,
4412        "occurrence": False,
4413        "group": False,
4414    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4417class RegexpLike(Func):
4418    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4421class RegexpILike(Func):
4422    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4427class RegexpSplit(Func):
4428    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4431class Repeat(Func):
4432    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4435class Round(Func):
4436    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4439class RowNumber(Func):
4440    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4443class SafeDivide(Func):
4444    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4447class SetAgg(AggFunc):
4448    pass
key = 'setagg'
class SHA(Func):
4451class SHA(Func):
4452    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4455class SHA2(Func):
4456    _sql_names = ["SHA2"]
4457    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4460class SortArray(Func):
4461    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4464class Split(Func):
4465    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4470class Substring(Func):
4471    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4474class StandardHash(Func):
4475    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4478class StrPosition(Func):
4479    arg_types = {
4480        "this": True,
4481        "substr": True,
4482        "position": False,
4483        "instance": False,
4484    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4487class StrToDate(Func):
4488    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4491class StrToTime(Func):
4492    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4497class StrToUnix(Func):
4498    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4501class NumberToStr(Func):
4502    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4505class FromBase(Func):
4506    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4509class Struct(Func):
4510    arg_types = {"expressions": True}
4511    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4514class StructExtract(Func):
4515    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4518class Sum(AggFunc):
4519    pass
key = 'sum'
class Sqrt(Func):
4522class Sqrt(Func):
4523    pass
key = 'sqrt'
class Stddev(AggFunc):
4526class Stddev(AggFunc):
4527    pass
key = 'stddev'
class StddevPop(AggFunc):
4530class StddevPop(AggFunc):
4531    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4534class StddevSamp(AggFunc):
4535    pass
key = 'stddevsamp'
class TimeToStr(Func):
4538class TimeToStr(Func):
4539    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4542class TimeToTimeStr(Func):
4543    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4546class TimeToUnix(Func):
4547    pass
key = 'timetounix'
class TimeStrToDate(Func):
4550class TimeStrToDate(Func):
4551    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4554class TimeStrToTime(Func):
4555    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4558class TimeStrToUnix(Func):
4559    pass
key = 'timestrtounix'
class Trim(Func):
4562class Trim(Func):
4563    arg_types = {
4564        "this": True,
4565        "expression": False,
4566        "position": False,
4567        "collation": False,
4568    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4571class TsOrDsAdd(Func, TimeUnit):
4572    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4575class TsOrDsToDateStr(Func):
4576    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4579class TsOrDsToDate(Func):
4580    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4583class TsOrDiToDi(Func):
4584    pass
key = 'tsorditodi'
class Unhex(Func):
4587class Unhex(Func):
4588    pass
key = 'unhex'
class UnixToStr(Func):
4591class UnixToStr(Func):
4592    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4597class UnixToTime(Func):
4598    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4599
4600    SECONDS = Literal.string("seconds")
4601    MILLIS = Literal.string("millis")
4602    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4605class UnixToTimeStr(Func):
4606    pass
key = 'unixtotimestr'
class Upper(Func):
4609class Upper(Func):
4610    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4613class Variance(AggFunc):
4614    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4617class VariancePop(AggFunc):
4618    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4621class Week(Func):
4622    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4625class XMLTable(Func):
4626    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4629class Year(Func):
4630    pass
key = 'year'
class Use(Expression):
4633class Use(Expression):
4634    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4637class Merge(Expression):
4638    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
4641class When(Func):
4642    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
4647class NextValueFor(Func):
4648    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4685def maybe_parse(
4686    sql_or_expression: ExpOrStr,
4687    *,
4688    into: t.Optional[IntoType] = None,
4689    dialect: DialectType = None,
4690    prefix: t.Optional[str] = None,
4691    copy: bool = False,
4692    **opts,
4693) -> Expression:
4694    """Gracefully handle a possible string or expression.
4695
4696    Example:
4697        >>> maybe_parse("1")
4698        (LITERAL this: 1, is_string: False)
4699        >>> maybe_parse(to_identifier("x"))
4700        (IDENTIFIER this: x, quoted: False)
4701
4702    Args:
4703        sql_or_expression: the SQL code string or an expression
4704        into: the SQLGlot Expression to parse into
4705        dialect: the dialect used to parse the input expressions (in the case that an
4706            input expression is a SQL string).
4707        prefix: a string to prefix the sql with before it gets parsed
4708            (automatically includes a space)
4709        copy: whether or not to copy the expression.
4710        **opts: other options to use to parse the input expressions (again, in the case
4711            that an input expression is a SQL string).
4712
4713    Returns:
4714        Expression: the parsed or given expression.
4715    """
4716    if isinstance(sql_or_expression, Expression):
4717        if copy:
4718            return sql_or_expression.copy()
4719        return sql_or_expression
4720
4721    if sql_or_expression is None:
4722        raise ParseError(f"SQL cannot be None")
4723
4724    import sqlglot
4725
4726    sql = str(sql_or_expression)
4727    if prefix:
4728        sql = f"{prefix} {sql}"
4729
4730    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4914def union(
4915    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4916) -> Union:
4917    """
4918    Initializes a syntax tree from one UNION expression.
4919
4920    Example:
4921        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4922        'SELECT * FROM foo UNION SELECT * FROM bla'
4923
4924    Args:
4925        left: the SQL code string corresponding to the left-hand side.
4926            If an `Expression` instance is passed, it will be used as-is.
4927        right: the SQL code string corresponding to the right-hand side.
4928            If an `Expression` instance is passed, it will be used as-is.
4929        distinct: set the DISTINCT flag if and only if this is true.
4930        dialect: the dialect used to parse the input expression.
4931        opts: other options to use to parse the input expressions.
4932
4933    Returns:
4934        The new Union instance.
4935    """
4936    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4937    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4938
4939    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
4942def intersect(
4943    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4944) -> Intersect:
4945    """
4946    Initializes a syntax tree from one INTERSECT expression.
4947
4948    Example:
4949        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4950        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4951
4952    Args:
4953        left: the SQL code string corresponding to the left-hand side.
4954            If an `Expression` instance is passed, it will be used as-is.
4955        right: the SQL code string corresponding to the right-hand side.
4956            If an `Expression` instance is passed, it will be used as-is.
4957        distinct: set the DISTINCT flag if and only if this is true.
4958        dialect: the dialect used to parse the input expression.
4959        opts: other options to use to parse the input expressions.
4960
4961    Returns:
4962        The new Intersect instance.
4963    """
4964    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4965    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4966
4967    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
4970def except_(
4971    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4972) -> Except:
4973    """
4974    Initializes a syntax tree from one EXCEPT expression.
4975
4976    Example:
4977        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4978        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4979
4980    Args:
4981        left: the SQL code string corresponding to the left-hand side.
4982            If an `Expression` instance is passed, it will be used as-is.
4983        right: the SQL code string corresponding to the right-hand side.
4984            If an `Expression` instance is passed, it will be used as-is.
4985        distinct: set the DISTINCT flag if and only if this is true.
4986        dialect: the dialect used to parse the input expression.
4987        opts: other options to use to parse the input expressions.
4988
4989    Returns:
4990        The new Except instance.
4991    """
4992    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4993    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4994
4995    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4998def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4999    """
5000    Initializes a syntax tree from one or multiple SELECT expressions.
5001
5002    Example:
5003        >>> select("col1", "col2").from_("tbl").sql()
5004        'SELECT col1, col2 FROM tbl'
5005
5006    Args:
5007        *expressions: the SQL code string to parse as the expressions of a
5008            SELECT statement. If an Expression instance is passed, this is used as-is.
5009        dialect: the dialect used to parse the input expressions (in the case that an
5010            input expression is a SQL string).
5011        **opts: other options to use to parse the input expressions (again, in the case
5012            that an input expression is a SQL string).
5013
5014    Returns:
5015        Select: the syntax tree for the SELECT statement.
5016    """
5017    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5020def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5021    """
5022    Initializes a syntax tree from a FROM expression.
5023
5024    Example:
5025        >>> from_("tbl").select("col1", "col2").sql()
5026        'SELECT col1, col2 FROM tbl'
5027
5028    Args:
5029        *expression: the SQL code string to parse as the FROM expressions of a
5030            SELECT statement. If an Expression instance is passed, this is used as-is.
5031        dialect: the dialect used to parse the input expression (in the case that the
5032            input expression is a SQL string).
5033        **opts: other options to use to parse the input expressions (again, in the case
5034            that the input expression is a SQL string).
5035
5036    Returns:
5037        Select: the syntax tree for the SELECT statement.
5038    """
5039    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5042def update(
5043    table: str | Table,
5044    properties: dict,
5045    where: t.Optional[ExpOrStr] = None,
5046    from_: t.Optional[ExpOrStr] = None,
5047    dialect: DialectType = None,
5048    **opts,
5049) -> Update:
5050    """
5051    Creates an update statement.
5052
5053    Example:
5054        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5055        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5056
5057    Args:
5058        *properties: dictionary of properties to set which are
5059            auto converted to sql objects eg None -> NULL
5060        where: sql conditional parsed into a WHERE statement
5061        from_: sql statement parsed into a FROM statement
5062        dialect: the dialect used to parse the input expressions.
5063        **opts: other options to use to parse the input expressions.
5064
5065    Returns:
5066        Update: the syntax tree for the UPDATE statement.
5067    """
5068    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5069    update_expr.set(
5070        "expressions",
5071        [
5072            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5073            for k, v in properties.items()
5074        ],
5075    )
5076    if from_:
5077        update_expr.set(
5078            "from",
5079            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5080        )
5081    if isinstance(where, Condition):
5082        where = Where(this=where)
5083    if where:
5084        update_expr.set(
5085            "where",
5086            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5087        )
5088    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5091def delete(
5092    table: ExpOrStr,
5093    where: t.Optional[ExpOrStr] = None,
5094    returning: t.Optional[ExpOrStr] = None,
5095    dialect: DialectType = None,
5096    **opts,
5097) -> Delete:
5098    """
5099    Builds a delete statement.
5100
5101    Example:
5102        >>> delete("my_table", where="id > 1").sql()
5103        'DELETE FROM my_table WHERE id > 1'
5104
5105    Args:
5106        where: sql conditional parsed into a WHERE statement
5107        returning: sql conditional parsed into a RETURNING statement
5108        dialect: the dialect used to parse the input expressions.
5109        **opts: other options to use to parse the input expressions.
5110
5111    Returns:
5112        Delete: the syntax tree for the DELETE statement.
5113    """
5114    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5115    if where:
5116        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5117    if returning:
5118        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5119    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5122def insert(
5123    expression: ExpOrStr,
5124    into: ExpOrStr,
5125    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5126    overwrite: t.Optional[bool] = None,
5127    dialect: DialectType = None,
5128    copy: bool = True,
5129    **opts,
5130) -> Insert:
5131    """
5132    Builds an INSERT statement.
5133
5134    Example:
5135        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5136        'INSERT INTO tbl VALUES (1, 2, 3)'
5137
5138    Args:
5139        expression: the sql string or expression of the INSERT statement
5140        into: the tbl to insert data to.
5141        columns: optionally the table's column names.
5142        overwrite: whether to INSERT OVERWRITE or not.
5143        dialect: the dialect used to parse the input expressions.
5144        copy: whether or not to copy the expression.
5145        **opts: other options to use to parse the input expressions.
5146
5147    Returns:
5148        Insert: the syntax tree for the INSERT statement.
5149    """
5150    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5151    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5152
5153    if columns:
5154        this = _apply_list_builder(
5155            *columns,
5156            instance=Schema(this=this),
5157            arg="expressions",
5158            into=Identifier,
5159            copy=False,
5160            dialect=dialect,
5161            **opts,
5162        )
5163
5164    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5167def condition(
5168    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5169) -> Condition:
5170    """
5171    Initialize a logical condition expression.
5172
5173    Example:
5174        >>> condition("x=1").sql()
5175        'x = 1'
5176
5177        This is helpful for composing larger logical syntax trees:
5178        >>> where = condition("x=1")
5179        >>> where = where.and_("y=1")
5180        >>> Select().from_("tbl").select("*").where(where).sql()
5181        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5182
5183    Args:
5184        *expression: the SQL code string to parse.
5185            If an Expression instance is passed, this is used as-is.
5186        dialect: the dialect used to parse the input expression (in the case that the
5187            input expression is a SQL string).
5188        copy: Whether or not to copy `expression` (only applies to expressions).
5189        **opts: other options to use to parse the input expressions (again, in the case
5190            that the input expression is a SQL string).
5191
5192    Returns:
5193        The new Condition instance
5194    """
5195    return maybe_parse(
5196        expression,
5197        into=Condition,
5198        dialect=dialect,
5199        copy=copy,
5200        **opts,
5201    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5204def and_(
5205    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5206) -> Condition:
5207    """
5208    Combine multiple conditions with an AND logical operator.
5209
5210    Example:
5211        >>> and_("x=1", and_("y=1", "z=1")).sql()
5212        'x = 1 AND (y = 1 AND z = 1)'
5213
5214    Args:
5215        *expressions: the SQL code strings to parse.
5216            If an Expression instance is passed, this is used as-is.
5217        dialect: the dialect used to parse the input expression.
5218        copy: whether or not to copy `expressions` (only applies to Expressions).
5219        **opts: other options to use to parse the input expressions.
5220
5221    Returns:
5222        And: the new condition
5223    """
5224    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5227def or_(
5228    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5229) -> Condition:
5230    """
5231    Combine multiple conditions with an OR logical operator.
5232
5233    Example:
5234        >>> or_("x=1", or_("y=1", "z=1")).sql()
5235        'x = 1 OR (y = 1 OR z = 1)'
5236
5237    Args:
5238        *expressions: the SQL code strings to parse.
5239            If an Expression instance is passed, this is used as-is.
5240        dialect: the dialect used to parse the input expression.
5241        copy: whether or not to copy `expressions` (only applies to Expressions).
5242        **opts: other options to use to parse the input expressions.
5243
5244    Returns:
5245        Or: the new condition
5246    """
5247    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5250def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5251    """
5252    Wrap a condition with a NOT operator.
5253
5254    Example:
5255        >>> not_("this_suit='black'").sql()
5256        "NOT this_suit = 'black'"
5257
5258    Args:
5259        expression: the SQL code string to parse.
5260            If an Expression instance is passed, this is used as-is.
5261        dialect: the dialect used to parse the input expression.
5262        copy: whether to copy the expression or not.
5263        **opts: other options to use to parse the input expressions.
5264
5265    Returns:
5266        The new condition.
5267    """
5268    this = condition(
5269        expression,
5270        dialect=dialect,
5271        copy=copy,
5272        **opts,
5273    )
5274    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5277def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5278    """
5279    Wrap an expression in parentheses.
5280
5281    Example:
5282        >>> paren("5 + 3").sql()
5283        '(5 + 3)'
5284
5285    Args:
5286        expression: the SQL code string to parse.
5287            If an Expression instance is passed, this is used as-is.
5288        copy: whether to copy the expression or not.
5289
5290    Returns:
5291        The wrapped expression.
5292    """
5293    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5311def to_identifier(name, quoted=None, copy=True):
5312    """Builds an identifier.
5313
5314    Args:
5315        name: The name to turn into an identifier.
5316        quoted: Whether or not force quote the identifier.
5317        copy: Whether or not to copy a passed in Identefier node.
5318
5319    Returns:
5320        The identifier ast node.
5321    """
5322
5323    if name is None:
5324        return None
5325
5326    if isinstance(name, Identifier):
5327        identifier = _maybe_copy(name, copy)
5328    elif isinstance(name, str):
5329        identifier = Identifier(
5330            this=name,
5331            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5332        )
5333    else:
5334        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5335    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5341def to_interval(interval: str | Literal) -> Interval:
5342    """Builds an interval expression from a string like '1 day' or '5 months'."""
5343    if isinstance(interval, Literal):
5344        if not interval.is_string:
5345            raise ValueError("Invalid interval string.")
5346
5347        interval = interval.this
5348
5349    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5350
5351    if not interval_parts:
5352        raise ValueError("Invalid interval string.")
5353
5354    return Interval(
5355        this=Literal.string(interval_parts.group(1)),
5356        unit=Var(this=interval_parts.group(2)),
5357    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5370def to_table(
5371    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5372) -> t.Optional[Table]:
5373    """
5374    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5375    If a table is passed in then that table is returned.
5376
5377    Args:
5378        sql_path: a `[catalog].[schema].[table]` string.
5379        dialect: the source dialect according to which the table name will be parsed.
5380        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5381
5382    Returns:
5383        A table expression.
5384    """
5385    if sql_path is None or isinstance(sql_path, Table):
5386        return sql_path
5387    if not isinstance(sql_path, str):
5388        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5389
5390    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5391    if table:
5392        for k, v in kwargs.items():
5393            table.set(k, v)
5394
5395    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5398def to_column(sql_path: str | Column, **kwargs) -> Column:
5399    """
5400    Create a column from a `[table].[column]` sql path. Schema is optional.
5401
5402    If a column is passed in then that column is returned.
5403
5404    Args:
5405        sql_path: `[table].[column]` string
5406    Returns:
5407        Table: A column expression
5408    """
5409    if sql_path is None or isinstance(sql_path, Column):
5410        return sql_path
5411    if not isinstance(sql_path, str):
5412        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5413    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5416def alias_(
5417    expression: ExpOrStr,
5418    alias: str | Identifier,
5419    table: bool | t.Sequence[str | Identifier] = False,
5420    quoted: t.Optional[bool] = None,
5421    dialect: DialectType = None,
5422    copy: bool = True,
5423    **opts,
5424):
5425    """Create an Alias expression.
5426
5427    Example:
5428        >>> alias_('foo', 'bar').sql()
5429        'foo AS bar'
5430
5431        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5432        '(SELECT 1, 2) AS bar(a, b)'
5433
5434    Args:
5435        expression: the SQL code strings to parse.
5436            If an Expression instance is passed, this is used as-is.
5437        alias: the alias name to use. If the name has
5438            special characters it is quoted.
5439        table: Whether or not to create a table alias, can also be a list of columns.
5440        quoted: whether or not to quote the alias
5441        dialect: the dialect used to parse the input expression.
5442        copy: Whether or not to copy the expression.
5443        **opts: other options to use to parse the input expressions.
5444
5445    Returns:
5446        Alias: the aliased expression
5447    """
5448    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5449    alias = to_identifier(alias, quoted=quoted)
5450
5451    if table:
5452        table_alias = TableAlias(this=alias)
5453        exp.set("alias", table_alias)
5454
5455        if not isinstance(table, bool):
5456            for column in table:
5457                table_alias.append("columns", to_identifier(column, quoted=quoted))
5458
5459        return exp
5460
5461    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5462    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5463    # for the complete Window expression.
5464    #
5465    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5466
5467    if "alias" in exp.arg_types and not isinstance(exp, Window):
5468        exp.set("alias", alias)
5469        return exp
5470    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5473def subquery(
5474    expression: ExpOrStr,
5475    alias: t.Optional[Identifier | str] = None,
5476    dialect: DialectType = None,
5477    **opts,
5478) -> Select:
5479    """
5480    Build a subquery expression.
5481
5482    Example:
5483        >>> subquery('select x from tbl', 'bar').select('x').sql()
5484        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5485
5486    Args:
5487        expression: the SQL code strings to parse.
5488            If an Expression instance is passed, this is used as-is.
5489        alias: the alias name to use.
5490        dialect: the dialect used to parse the input expression.
5491        **opts: other options to use to parse the input expressions.
5492
5493    Returns:
5494        A new Select instance with the subquery expression included.
5495    """
5496
5497    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5498    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5501def column(
5502    col: str | Identifier,
5503    table: t.Optional[str | Identifier] = None,
5504    db: t.Optional[str | Identifier] = None,
5505    catalog: t.Optional[str | Identifier] = None,
5506    quoted: t.Optional[bool] = None,
5507) -> Column:
5508    """
5509    Build a Column.
5510
5511    Args:
5512        col: Column name.
5513        table: Table name.
5514        db: Database name.
5515        catalog: Catalog name.
5516        quoted: Whether to force quotes on the column's identifiers.
5517
5518    Returns:
5519        The new Column instance.
5520    """
5521    return Column(
5522        this=to_identifier(col, quoted=quoted),
5523        table=to_identifier(table, quoted=quoted),
5524        db=to_identifier(db, quoted=quoted),
5525        catalog=to_identifier(catalog, quoted=quoted),
5526    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5529def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5530    """Cast an expression to a data type.
5531
5532    Example:
5533        >>> cast('x + 1', 'int').sql()
5534        'CAST(x + 1 AS INT)'
5535
5536    Args:
5537        expression: The expression to cast.
5538        to: The datatype to cast to.
5539
5540    Returns:
5541        The new Cast instance.
5542    """
5543    expression = maybe_parse(expression, **opts)
5544    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5547def table_(
5548    table: Identifier | str,
5549    db: t.Optional[Identifier | str] = None,
5550    catalog: t.Optional[Identifier | str] = None,
5551    quoted: t.Optional[bool] = None,
5552    alias: t.Optional[Identifier | str] = None,
5553) -> Table:
5554    """Build a Table.
5555
5556    Args:
5557        table: Table name.
5558        db: Database name.
5559        catalog: Catalog name.
5560        quote: Whether to force quotes on the table's identifiers.
5561        alias: Table's alias.
5562
5563    Returns:
5564        The new Table instance.
5565    """
5566    return Table(
5567        this=to_identifier(table, quoted=quoted),
5568        db=to_identifier(db, quoted=quoted),
5569        catalog=to_identifier(catalog, quoted=quoted),
5570        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5571    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5574def values(
5575    values: t.Iterable[t.Tuple[t.Any, ...]],
5576    alias: t.Optional[str] = None,
5577    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5578) -> Values:
5579    """Build VALUES statement.
5580
5581    Example:
5582        >>> values([(1, '2')]).sql()
5583        "VALUES (1, '2')"
5584
5585    Args:
5586        values: values statements that will be converted to SQL
5587        alias: optional alias
5588        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5589         If either are provided then an alias is also required.
5590
5591    Returns:
5592        Values: the Values expression object
5593    """
5594    if columns and not alias:
5595        raise ValueError("Alias is required when providing columns")
5596
5597    return Values(
5598        expressions=[convert(tup) for tup in values],
5599        alias=(
5600            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5601            if columns
5602            else (TableAlias(this=to_identifier(alias)) if alias else None)
5603        ),
5604    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5607def var(name: t.Optional[ExpOrStr]) -> Var:
5608    """Build a SQL variable.
5609
5610    Example:
5611        >>> repr(var('x'))
5612        '(VAR this: x)'
5613
5614        >>> repr(var(column('x', table='y')))
5615        '(VAR this: x)'
5616
5617    Args:
5618        name: The name of the var or an expression who's name will become the var.
5619
5620    Returns:
5621        The new variable node.
5622    """
5623    if not name:
5624        raise ValueError("Cannot convert empty name into var.")
5625
5626    if isinstance(name, Expression):
5627        name = name.name
5628    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5631def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5632    """Build ALTER TABLE... RENAME... expression
5633
5634    Args:
5635        old_name: The old name of the table
5636        new_name: The new name of the table
5637
5638    Returns:
5639        Alter table expression
5640    """
5641    old_table = to_table(old_name)
5642    new_table = to_table(new_name)
5643    return AlterTable(
5644        this=old_table,
5645        actions=[
5646            RenameTable(this=new_table),
5647        ],
5648    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5651def convert(value: t.Any, copy: bool = False) -> Expression:
5652    """Convert a python value into an expression object.
5653
5654    Raises an error if a conversion is not possible.
5655
5656    Args:
5657        value: A python object.
5658        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5659
5660    Returns:
5661        Expression: the equivalent expression object.
5662    """
5663    if isinstance(value, Expression):
5664        return _maybe_copy(value, copy)
5665    if isinstance(value, str):
5666        return Literal.string(value)
5667    if isinstance(value, bool):
5668        return Boolean(this=value)
5669    if value is None or (isinstance(value, float) and math.isnan(value)):
5670        return NULL
5671    if isinstance(value, numbers.Number):
5672        return Literal.number(value)
5673    if isinstance(value, datetime.datetime):
5674        datetime_literal = Literal.string(
5675            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5676        )
5677        return TimeStrToTime(this=datetime_literal)
5678    if isinstance(value, datetime.date):
5679        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5680        return DateStrToDate(this=date_literal)
5681    if isinstance(value, tuple):
5682        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5683    if isinstance(value, list):
5684        return Array(expressions=[convert(v, copy=copy) for v in value])
5685    if isinstance(value, dict):
5686        return Map(
5687            keys=[convert(k, copy=copy) for k in value],
5688            values=[convert(v, copy=copy) for v in value.values()],
5689        )
5690    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5693def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5694    """
5695    Replace children of an expression with the result of a lambda fun(child) -> exp.
5696    """
5697    for k, v in expression.args.items():
5698        is_list_arg = type(v) is list
5699
5700        child_nodes = v if is_list_arg else [v]
5701        new_child_nodes = []
5702
5703        for cn in child_nodes:
5704            if isinstance(cn, Expression):
5705                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5706                    new_child_nodes.append(child_node)
5707                    child_node.parent = expression
5708                    child_node.arg_key = k
5709            else:
5710                new_child_nodes.append(cn)
5711
5712        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5715def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5716    """
5717    Return all table names referenced through columns in an expression.
5718
5719    Example:
5720        >>> import sqlglot
5721        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5722        ['a', 'c']
5723
5724    Args:
5725        expression: expression to find table names.
5726        exclude: a table name to exclude
5727
5728    Returns:
5729        A list of unique names.
5730    """
5731    return {
5732        table
5733        for table in (column.table for column in expression.find_all(Column))
5734        if table and table != exclude
5735    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: sqlglot.expressions.Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
5738def table_name(table: Table | str, dialect: DialectType = None) -> str:
5739    """Get the full name of a table as a string.
5740
5741    Args:
5742        table: Table expression node or string.
5743        dialect: The dialect to generate the table name for.
5744
5745    Examples:
5746        >>> from sqlglot import exp, parse_one
5747        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5748        'a.b.c'
5749
5750    Returns:
5751        The table name.
5752    """
5753
5754    table = maybe_parse(table, into=Table)
5755
5756    if not table:
5757        raise ValueError(f"Cannot parse {table}")
5758
5759    return ".".join(
5760        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5761        for part in table.parts
5762    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
5765def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5766    """Replace all tables in expression according to the mapping.
5767
5768    Args:
5769        expression: expression node to be transformed and replaced.
5770        mapping: mapping of table names.
5771        copy: whether or not to copy the expression.
5772
5773    Examples:
5774        >>> from sqlglot import exp, parse_one
5775        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5776        'SELECT * FROM c'
5777
5778    Returns:
5779        The mapped expression.
5780    """
5781
5782    def _replace_tables(node: Expression) -> Expression:
5783        if isinstance(node, Table):
5784            new_name = mapping.get(table_name(node))
5785            if new_name:
5786                return to_table(
5787                    new_name,
5788                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5789                )
5790        return node
5791
5792    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5795def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5796    """Replace placeholders in an expression.
5797
5798    Args:
5799        expression: expression node to be transformed and replaced.
5800        args: positional names that will substitute unnamed placeholders in the given order.
5801        kwargs: keyword arguments that will substitute named placeholders.
5802
5803    Examples:
5804        >>> from sqlglot import exp, parse_one
5805        >>> replace_placeholders(
5806        ...     parse_one("select * from :tbl where ? = ?"),
5807        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5808        ... ).sql()
5809        "SELECT * FROM foo WHERE str_col = 'b'"
5810
5811    Returns:
5812        The mapped expression.
5813    """
5814
5815    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5816        if isinstance(node, Placeholder):
5817            if node.name:
5818                new_name = kwargs.get(node.name)
5819                if new_name:
5820                    return convert(new_name)
5821            else:
5822                try:
5823                    return convert(next(args))
5824                except StopIteration:
5825                    pass
5826        return node
5827
5828    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5831def expand(
5832    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5833) -> Expression:
5834    """Transforms an expression by expanding all referenced sources into subqueries.
5835
5836    Examples:
5837        >>> from sqlglot import parse_one
5838        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5839        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5840
5841        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5842        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5843
5844    Args:
5845        expression: The expression to expand.
5846        sources: A dictionary of name to Subqueryables.
5847        copy: Whether or not to copy the expression during transformation. Defaults to True.
5848
5849    Returns:
5850        The transformed expression.
5851    """
5852
5853    def _expand(node: Expression):
5854        if isinstance(node, Table):
5855            name = table_name(node)
5856            source = sources.get(name)
5857            if source:
5858                subquery = source.subquery(node.alias or name)
5859                subquery.comments = [f"source: {name}"]
5860                return subquery.transform(_expand, copy=False)
5861        return node
5862
5863    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5866def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5867    """
5868    Returns a Func expression.
5869
5870    Examples:
5871        >>> func("abs", 5).sql()
5872        'ABS(5)'
5873
5874        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5875        'CAST(5 AS DOUBLE)'
5876
5877    Args:
5878        name: the name of the function to build.
5879        args: the args used to instantiate the function of interest.
5880        dialect: the source dialect.
5881        kwargs: the kwargs used to instantiate the function of interest.
5882
5883    Note:
5884        The arguments `args` and `kwargs` are mutually exclusive.
5885
5886    Returns:
5887        An instance of the function of interest, or an anonymous function, if `name` doesn't
5888        correspond to an existing `sqlglot.expressions.Func` class.
5889    """
5890    if args and kwargs:
5891        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5892
5893    from sqlglot.dialects.dialect import Dialect
5894
5895    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5896    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5897
5898    parser = Dialect.get_or_raise(dialect)().parser()
5899    from_args_list = parser.FUNCTIONS.get(name.upper())
5900
5901    if from_args_list:
5902        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5903    else:
5904        kwargs = kwargs or {"expressions": converted}
5905        function = Anonymous(this=name, **kwargs)
5906
5907    for error_message in function.error_messages(converted):
5908        raise ValueError(error_message)
5909
5910    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5913def true() -> Boolean:
5914    """
5915    Returns a true Boolean expression.
5916    """
5917    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5920def false() -> Boolean:
5921    """
5922    Returns a false Boolean expression.
5923    """
5924    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5927def null() -> Null:
5928    """
5929    Returns a Null expression.
5930    """
5931    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )